The right way to compare a System.Double to '0' (a number, int?)

Viewed 113279

I have this if expression,

void Foo()
{
    System.Double something = GetSomething();
    if (something == 0) //Comparison of floating point numbers with equality 
                     // operator. Possible loss of precision while rounding value
        {}
}

Is that expression equal with

void Foo()
{
    System.Double something = GetSomething();
    if (something < 1)
        {}
}

? Because then I might have a problem, entering the if with e.g. a value of 0.9.

7 Answers

Here is the example presenting the problem (prepared in LinQPad - if you don't have it just use Console.Writeline instead of Dump method):

void Main()
{
    double x = 0.000001 / 0.1;
    double y = 0.001 * 0.01; 

    double res = (x-y);
    res.Dump();
    (res == 0).Dump();
}

Both x and y are theoretically same and equal to: 0.00001 but because of lack of "infinite precision" those values are slightly different. Unfortunately slightly enough to return false when comparing to 0 in usual way.

Prefer this method when you want to check how close is the double value to zero for both signs.

public static bool isZero(double value, double precision = 1e-6)
{
    return !value.Equals(double.NaN) && 
           !value.Equals(double.NegativeInfinity) && 
           !value.Equals(double.PositiveInfinity) && 
           Math.Abs(value) < precision;
}
Related