How do you test to see if a double is equal to NaN?
Use Double.isNaN(value)
to check if a double
is NaN
. Direct comparisons with NaN
such as value == Double.NaN
will not work, since in the realm of floating point numbers, NaN
is considered unequal to any value, including itself. Here's a quick example to illustrate this:
This method is built into the Java's Double
class and provides a reliable check for NaN
.
In-depth: Getting to know NaN
In Java, NaN
stands for Not-a-Number. It's a special double
value that represents the result of an undefined or unrepresentable mathematical operation.
The failed equality operation
Directly comparing a double
value to Double.NaN
always yields false
. This is due to NaN
's special property:
The above operation fails because of the IEEE 754
floating-point standard, which states NaN
is unequal to any value, even itself (NaN knows the importance of being unique).
NaN != NaN? Yes, indeed!
Consequently, a double
value allows a rather strange operation where NaN
is not equal (!=
) to NaN
. While this may appear incorrect, it correctly follows the IEEE 754
standard:
Using isNaN() with Double objects
When dealing with Double
objects (the object form of the primitive double
), you can use the object's isNaN()
method:
This is particularly useful when working with Double objects rather than primitive double
.
Protecting against null and NaN
In situations where you're dealing with Double
objects that could potentially be null
or NaN
, you can perform a compound check:
NaN in the wild: Use-cases and edge cases
Don't let NaN sneak into your calculations
NaN
can result from certain mathematical operations and can propagate through your calculations:
Testing for NaN in unit tests with JUnit
JUnit offers the assertEquals()
method that accepts NaN
as a valid argument:
Remember, a good unit test is as clear as your future with clean code!
Dealing with NaN during comparisons
When dealing with comparisons involving NaN
, consider using special tools like the Comparator
interface in Java:
This allows us to make NaN
friendly comparisons (because apparently NaN has feelings too).
References
Was this article helpful?