C# double equality
Author: Shourui
Creation Date: 10/24/2010 9:26 PM
profile picture

Shourui

#1

CODE:
Please log in to see this code.


Debug window output is:
0.2
0.2
False
1

I don't know why the logic value in line 3 is false when both values are equal to 0.2. Any help will be appreciated
profile picture

Sammy_G

#2
A couple of suggestions:

Make sure you are looking at the full double value in the debug window; perhaps there's a tiny difference at the nth decimal place?

Also, make sure both variables are declared as "double", or are converted to double, somewhere in the script. If one value is, say, an integer and the other is a double (though they both appear to be double), then division may not give a double value for result.
profile picture

Eugene

#3
QUOTE:
I don't know why the logic value in line 3 is false when both values are equal to 0.2.

Sammy_G makes a good point. Or to quote MSDN for double.Equals:
QUOTE:
Precision in Comparisons

The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. Consequently, a comparison of two particular numbers might change between versions of the .NET Framework because the precision of the numbers' internal representation might change.
profile picture

Cone

#4
QUOTE:
Make sure you are looking at the full double value in the debug window; perhaps there's a tiny difference at the nth decimal place?
Believe it or not, I've even seen a case in which two numbers displayed at full precision were precisely the same, but an equality test fails.

The point is that you should never test floating point numbers for equality. There are many ways to do it, but if you don't want to resort to string conversion, here's probably the best method:

CODE:
Please log in to see this code.
Note that "significant digits" are not the same as numbers to the right of the decimal. In other words, the function adapts to the size of the numbers being compared.
profile picture

Shourui

#5
Thanks for all helps.
profile picture

Eugene

#6
Also, a static AlmostEquals method exists in Community.Components for a long time.
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).