Why does Resharper complain when I compare a double to zero?
Since R# 6, many such inspections have a 'Why is ReSharper suggesting this?' item on their Alt+Enter menu. In this case, the explanation relates to the possible unintended consequences of doing equality comparisons on floating point values:
Using the
==
operator to compare floating-point numbers is, generally, a bad idea. The problem arises from the fact that, typically, results of calculations have to be ‘fitted’ into floating-point representation, which does not always matched the perceived reality of what result should be produced.
Resharper does not analyze how the double variable got its value.
After a few calculations a double value is rarely exact so resharper warns you that comparing a double with an exact value is not a good idea.
double x = Math.Sqrt(2);
double d = x * x;
Console.WriteLine(d == 2);
often calculation with double is inexact. comparing a double with an exact value may be problematic. Comparing with an intervallmight be more secure.
if ((d > -0.000001) && (d < +0.000001)) {
...
}
the same applies when comparing dates
if ((date >= DateTime.parse("2012-05-21T00:00:00")) &&
(date <= DateTime.parse("2012-05-21T23:59:59"))) {
}