1

Possible Duplicates:
C# float bug? 0.1 - 0.1 = 1.490116E-08
problem in comparing double values in C#

In my application I want to test if float a=float b, and then do some operations. But, I wonder, that in float type 0.2+0.3==0.5 is returning false .

So here is some part of my code

float a = 0.3f;
float b = 0.2f;
float c = 0.5f;
   if (a + b == c)
          Console.WriteLine("true");
   else 
          Console.WriteLine("false");
   Console.WriteLine(a+b);
   Console.WriteLine(c);

And here is result of this part

false
0.5
0.5

I can't figure out what is wrong here... I can use double or decimal instead float, but I want to know what's wrong here. Thanks for help.

Community
  • 1
  • 1
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
  • http://stackoverflow.com/questions/1398753/problem-in-comparing-double-values-in-c – fl00r Aug 19 '11 at 10:22
  • This answer should solve your problem: http://stackoverflow.com/questions/485175/c-net-is-it-safe-to-check-floating-point-values-for-equality-to-0/485777#485777 – ChrisA Aug 19 '11 at 10:24
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) – Paolo Falabella Aug 19 '11 at 10:24

1 Answers1

6

Floats are not exact values, they are approximates. It could be that the equation is 0.30000001 + 0.20000003 (= 0.50000004) == 0.50000001 which results in a false.

You should check if the difference between the 2 values is really small. More info here

RvdK
  • 19,580
  • 4
  • 64
  • 107