0

Now I understand floats are less accurate than double, but does this explain when I have the std::string:

"7.6317"

and I do:

float x = atof(myString.c_str());

getting 7.63170004 is expected? Is there any way I can tell the assignment of x to only read the first 4 decimal places? Or is this because of the way the float representation stores the number 7.6317?

user997112
  • 29,025
  • 43
  • 182
  • 361
  • No, a `float` cannot store X decimal places. You can tell it to print with a specific precision. And `double` has the same behaviour. And use `std::stof`. – chris Jul 27 '14 at 18:21
  • 2
    The closest float to 7.6317 is 7.631700038909912109375 – harold Jul 27 '14 at 18:31

3 Answers3

0

Yes. It is expected. It is so-called floating point error.

Midas
  • 169
  • 1
  • 1
  • 9
0

Some floating point literals do not have an accurate representation in the computer, even if -- in decimal notation -- the number seems harmless. This is because the computer uses 2 as a base. So even if a number might have a finite representation in base 10, it might not have on in base 2.

Oswald
  • 31,254
  • 3
  • 43
  • 68
-1

you can do it like:

float x = floorf(val * 10000) / 10000;

i think it should work! see See

Community
  • 1
  • 1
Exciter
  • 94
  • 6