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

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


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

// 1. static methodif (Double.isNaN(doubleValue)) {    ...}// 2. object's methodif (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.


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.


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)