-1

I'm parsing a file with some numbers. I'm trying to change the numbers from string to float or double, but I found out a precision problem with stof and stod, they are off by slight amount in VS C++. For example

string str1="3.14", str2="45.106";
double number1, number2;
number1=stod(str1);
number2=stof(str2);

When I test (number1==3.14), it returns "false". When I look in debugger, number1 is actually 3.139999999 or something like that! number2 may be 45.1060000002 or something like that. Any explanation or solution?

Eric Postpischil
  • 168,892
  • 12
  • 149
  • 276
Leigh Chao
  • 5
  • 1
  • 1
  • 2
    Explanation: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems. One need to take care when using equality comparisons with floating point types. – Zeta Mar 05 '13 at 20:33

1 Answers1

0

You may wish to take a look at this example:

How is floating point stored? When does it matter?

The thing to learn from this, is that it is almost never the solution to do a direct compare between two floating point numbers. You only have a certain amount of precision in floating point numbers, thus there is a limit to the precision you can expect, this is well put in the link in the comments by Zeta.

Community
  • 1
  • 1
Tommy Andersen
  • 6,928
  • 1
  • 28
  • 47