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

radbyx picture radbyx · Jul 6, 2011 · Viewed 91.2k times · Source

Sorry, this might be a easy stupid question, but I need to know to be sure.

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.

Answer

Jon Skeet picture Jon Skeet · Jul 6, 2011

Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.

Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:

if (Math.Abs(something) < 0.001)

The epsilon you should use is application-specific - it depends on what you're doing.

Of course, if the result should be exactly zero, then a simple equality check is fine.