-1

When I used VS 2015 to debug the following code,

int main()
{
    char thev[8] = "0.12345";
    float fv = atof(thev);
    printf("%f\n", fv);
    return 0;
}

the value of fv in watch window is 0.12345004, and printf is 0.123450, how to let fv=0.12345 in the run time?

There is similar post, here, but no answer there, can somebody help me?

And I pasted that code to my VS 2015,

int main()
{
    const char *val = "73.31";
    std::stringstream ss;
    ss << val;
    double doubleVal = 0.0f;
    ss >> doubleVal;
}

the value doubleVal in watch window is 73.310000000000002

Ben
  • 9
  • 4
  • 1
    Better read [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) It also contains links to other materials you should read to really understand what is going on. – user4581301 Jul 19 '18 at 01:43

2 Answers2

0

Replace the following code:

printf("%f\n", fv);

with:

printf("%.5f\n", fv);

Explaination:

we use a width (%.5f) to say that we want 5 digits (positions) reserved for the output. The result is that 5 “space characters” are placed before printing the character. And the next character will be not printed.

Reference: https://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

Marfin. F
  • 434
  • 4
  • 16
  • Marfin, I don't want to print it out, just want to let the fv=0.12345 in the runtime. – Ben Jul 19 '18 at 01:45
0

There is no exact representation in IEEE single precision for 0.12345. The closest two values on either side of it are 0.123450003564357757568359375 and 0.12344999611377716064453125. atof is picking the former, I think because it is closer to 0.12345 than the latter.

SCFrench
  • 8,244
  • 2
  • 31
  • 61