## #415 – Be Careful When Checking Floating Point Numbers for Equality

September 20, 2011 2 Comments

When you check two floating point numbers for equality in C#, you might sometimes be surprised at the result.

Consider the following example. **f2** is equal to six sixths (1.0), minus 1.0–which should be equal to 0.0. But when we compare the result to 0.0, we see that the values are not equal.

float f1 = 1.0f / 6.0f; float f2 = (f1 * 6.0f) - 1.0f; // Should be 0.0 float f3 = 0.0f; bool check = (f2 == f3); // Should be true, but is false !

This happens because floating point numbers can’t necessarily be represented exactly when stored in a floating point variable. Instead, the value stored can be very close, but not equal to, the desired value.

Here’s the output from the example above. **f2** should be equal to 0.0, after our calculation. It is instead *very nearly equal to *0.0. Because of this, the comparison to the constant 0.0 fails.