Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7036583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T01:26:29+00:00 2026-05-28T01:26:29+00:00

I found this happened when I was doing string-to-double converting exercise (e.g. atof in

  • 0

I found this happened when I was doing string-to-double converting exercise (e.g. atof in stdlib.h). I wanted to put string of “625” (which indicates a fraction part of a double) to a double variable 0.625. The strange thing is when I put it as part of my exercise, it resulted in inaccurate result 0.62500000000000011 or something alike. However, when I put it in a stand alone way, it worked fine, like the following code:

int main(int argc, char **argv) {
string str = "625";
double mask = 0.1;
double frac = 0.0;
for( int i = 0; i < static_cast<int>(str.length()); ++i ) {
    frac += (str[i] - '0')*mask;
    mask *= 0.1;
}
cout << frac << endl;

}

The code above give the accurate result (0.625). But the following code give the inaccurate result (0.62500000000000011):

string PrintDecimal(string input) {
    long int_part = 0;
    double frac_part = 0.0;
    bool is_positive;
    size_t found;
    string ret_str;
    found = input.find('-');
    if( found == string::npos ) {
        is_positive = true;
    }
    else {
        is_positive = false;
        input.erase(found, 1);
    }
    found = input.find('.');
    if( found == string::npos ) {
        int mask = 1; 
        char app_char;
        for( int i = static_cast<int>(input.length()-1); i > -1; --i ) {
            int_part += (input[i] - '0')*mask;
            mask *= 10;
        }
        while( int_part != 0 ) {
            app_char = (int_part % 2 == 0) ? '0' : '1';
            ret_str.push_back(app_char);
            int_part /= 2;
        }
        if( is_positive == false ) {
            ret_str.append("-");
        }
        reverse(ret_str.begin(), ret_str.end());
    }
    else {
        char app_char;
        long mask_int = 1;
        double mask_frac = 0.1;
        string int_part_str = input.substr(0, found);
        //string frac_part_str = input.substr(found+1, input.length()-found-1);
        string frac_part_str = "0."; 
        frac_part_str.append(input.substr(found+1, input.length()-found-1));
        for( int i = static_cast<int>(int_part_str.length()-1); i > -1; --i ) {
            int_part += (int_part_str[i] - '0')*mask_int;
            mask_int *= 10;
        }
        //This converting causes 6*0.1 = 0.6000000000009
        /*
        for( int i = 0; i < static_cast<int>(frac_part_str.length()); ++i ) {
            frac_part += (frac_part_str[i] - '0')*mask_frac;
            mask_frac *= 0.1;
        }
        */
        frac_part = atof(frac_part_str.c_str()); //This works well.
        while( int_part != 0 ) {
            app_char = (int_part % 2 == 0) ? '0' : '1';
            ret_str.push_back(app_char);
            int_part /= 2;
        }
        if( is_positive == false ) {
            ret_str.append("-");
        }
        reverse(ret_str.begin(), ret_str.end());
        ret_str.push_back('.');
        found = ret_str.find('.');
        while( frac_part != 0.0 ) {
            if( ret_str.length() - found > 64 ) {
                cerr << "Can't express accurately." << endl;
                return "Error";
            }
            frac_part *= 2;
            if( frac_part >= 1.0 ) {
                ret_str.push_back('1');
                frac_part -= 1;
            }
            else {
                ret_str.push_back('0');
            }
        }

    }
    cout << ret_str << endl;

    return ret_str;
}

The compiler version I used was gcc version 4.2.1 (Apple Inc. build 5666) (dot 3).
Please notice that the commented part in the code, which causes the problem. I ask for your ideas to give a solution to this problem. Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T01:26:30+00:00Added an answer on May 28, 2026 at 1:26 am

    Well, actually the first isn’t exact either, if we print the result out with more precision we get

    0.62500000000000011102
    

    and, printing the intermediate results to full precision

    Prelude Text.FShow.RealFloat> mapM_ print $ scanl (+) (FD 0) $ zipWith (*) (iterate (*0.1) 0.1) [6,2,5]
    0.0
    0.600000000000000088817841970012523233890533447265625
    0.62000000000000010658141036401502788066864013671875
    0.62500000000000011102230246251565404236316680908203125
    

    To get the most accurate result possible, you have to employ a more complicated algorithm, for example parse the string as a rational number and convert from that.

    A quick partial solution is to parse the fractional part to yield numerator / (10^k),

    double denominator = 1.0;
    uint64_t numerator = 0;
    for(i = f0; i < len; ++i) {  // f0 index of first digit after decimal point
        numerator = 10*numerator + (str[i] - '0');
        denominator *= 10;
    }
    double fractional_part = numerator / denominator;
    

    powers of 10 (with nonnegative exponent) can be represented exactly as doubles for a while (for exponents <= 22, assuming 64-bit IEEE754 doubles) and the numerator can be represented exactly too, if the fractional part is not too long. Then you have only one point where an inexact result occurs due to necessary rounding, the final division, and the result is (supposed to be) the closest representable number to the exact mathematical result. (A further point of inexactness is the addition of the fractional part to the integral part.)

    The above will produce good results for input with not too big integral part and short enough fractional parts, but it will be very wrong for long fractional parts.

    The correct parsing and displaying of floating point numbers is a complicated business.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I found myself staring at code that looks similar to this: private double? _foo;
This hasn't happened to me yet, but I found myself wondering if it is
Found this: Sub SurroundWithAppendTag() DTE.ActiveDocument.Selection.Text = .Append( + DTE.ActiveDocument.Selection.Text + ) End Sub But
found this regex: insert every 10 characters: $text = preg_replace(|(.{10})|u, \${1}. , $text); can
Found this rather strange bug in IE8; element.style.top is limited to 1342177 pixels. Even
Reading this question I found this as (note the quotation marks) code to solve
I found this open-source library that I want to use in my Java application.
I found this link http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/ , but there isn't a lot of description around
I found this in an article on Multithreaded Apartments, but can’t find a definition
Just found this out, so i am answering my own question :) Use a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.