I am trying to assert that my double is NaN. Here is a code snippet:
private Double calculateIt(String input){...}
assertEquals(Double.NaN, calculateIt("input text"));
The code does not compile, Double.NaN
is defined as primitive
public static final double NaN = 0.0d / 0.0;
To make the assertion work I wrap NaN with a Double object.
assertEquals(new Double(Double.NaN), calculateIt("input text"));
Is there a shorter way to do this?
Java Double isNaN() Method The 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.
Java defines NaN constants of both float and double types as Float. NaN and Double. NaN: “A constant holding a Not-a-Number (NaN) value of type double.
In mathematics, taking the square root of a negative number results in an imaginary number. This case is dealt with by returning NaN in Java. Taking mod of a number with zero, will return the remainder after dividing a value by zero. Hence, NaN is returned.
isNaN() method This method returns true if the value represented by this object is NaN; false otherwise.
You could use:
boolean isNan = Double.isNaN(calculateIt("input text"));
assertTrue(isNan);
Double.NaN
values cannot be compared with ==
(Double.NaN == Double.NaN
will return false
), because NaN
is considered as a special one.
More info:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With