Search code examples
c++precisionscanfatof

Why is there a loss in precision when converting char * to float using sscanf_s or atof?


I am trying to convert a char * containing just a floating point value to a type float, but both sscanf_s and atof both produce the same invalid result.

char t[] = "2.10";
float aFloat( 0.0f ), bFloat( 0.0f );

sscanf_s( t, "%f", &aFloat );
bFloat = atof( t );

Output:

aFloat: 2.09999990
bFloat: 2.09999990

When I looked at similar questions in an attempt to ascertain the answer I attempted their solutions to no avail.

Converting char* to float or double

The solution given here was to include 'stdlib.h', and after doing so I changed the call to atof to an explicit call 'std::atof', but still no luck.


Solution

  • Unfortunately, not all floating point values can be explicitly represented in binary form. You will get the same result if you say

    float myValue = 2.10;