Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can double Be NaN?

NaN: “A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.

How can you tell if a float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

What is the value of double NaN?

NaN values are tested for equality by using the == operator, the result is false. So, no matter what value of type double is compared with double. NaN, the result is always false.

Is NaN a double Java?

Java Double isNaN() MethodThe isNaN() method of Java Double class returns true: If the value of this Object is Not-a-Number (NaN). If the argument passed is Not-a-Number (NaN). Otherwise, the method returns false.


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.


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)

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.


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.