1

i am doing very basic calculations and getting the weird result when i am comparing double values in if.. statement. See the screenshot attached. enter image description here

I marked the variable value with Red markers. You can see the value of variable totalSliceValue is 100 and when i compared the value with 100.0 it return TRUE, but 100 is not greater than 100.

Can anybody explain this why i am getting this. Is there any bug in my code or it is an issue with the compiler.

Thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Vinay Jain
  • 2,644
  • 3
  • 26
  • 44

1 Answers1

1

When it's a double, 100 is often greater than 100. Or less. It is actually 100.000000000127832645 or something like that.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Another of many articles on the problem developers face when working with floats and doubles.

Solution: subtract one double for another and check that the result is so small that you can treat them as equal, not that they are equal.

One duplicate StackOverflow question

Another duplicate

The problem isn't really with the compiler but the way you are instructing it - it's working according to the rules for IEEE floating point.

Community
  • 1
  • 1
Adam Eberbach
  • 12,309
  • 6
  • 62
  • 114