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

ID : 10062

viewed : 35

Tags : javadoubleequalitynanjava

Top 5 Answer for java - How do you test to see if a double is equal to NaN?

vote vote

94

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.

vote vote

89

Try Double.isNaN():

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.

vote vote

71

You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.

/**  * Returns {@code true} if the argument is a finite floating-point  * value; returns {@code false} otherwise (for NaN and infinity  * arguments).  *  * @param d the {@code double} value to be tested  * @return {@code true} if the argument is a finite  * floating-point value, {@code false} otherwise.  * @since 1.8  */ public static boolean isFinite(double d) 
vote vote

60

You can check for NaN by using var != var. NaN does not equal NaN.

EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.

vote vote

57

If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

(value==null || Double.isNaN(value))

Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

Top 3 video Explaining java - How do you test to see if a double is equal to NaN?

Related QUESTION?