How do you test to see if a double is equal to NaN?

Eric Wilson picture Eric Wilson · Sep 21, 2009 · Viewed 189.3k times · Source

I have a double in Java and I want to check if it is NaN. What is the best way to do this?

Answer

Ben S picture Ben S · Sep 21, 2009

Use the static Double.isNaN(double) method, or your Double's .isNaN() method.

// 1. static method
if (Double.isNaN(doubleValue)) {
    ...
}
// 2. object's method
if (doubleObject.isNaN()) {
    ...
}

Simply doing:

if (var == Double.NaN) {
    ...
}

is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.