Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Resharper complain when I compare a double to zero?

If I do

double d = 0;
if (d == 0) {
  ...
}

Resharper complains at the comparison d == 0 about "Comparison of floating point number with equality operator. Possible loss of precision while rounding values."

Why? It cannot be difficult to represent exact zero as a double or a float can it?

I understand such a warning would be relevant if I compared to some other value such as 0.2 for which there is no exact binary representation.

like image 732
tomsv Avatar asked May 21 '12 11:05

tomsv


People also ask

Can you compare float and double?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float. For example, to store the annual salary of the CEO of a company, double will be a more accurate choice.

How do you compare double numbers in C#?

The Double. CompareTo() method in C# is used to compare this instance to a specified object or Double object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or Double object.


1 Answers

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);
like image 134
adrianm Avatar answered Oct 03 '22 13:10

adrianm