I have a double in Java and I want to check if it is NaN. What's the best way to do this?
+4
A:
Try double.isNaN():
Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
Andrew Hare
2009-09-21 20:11:00
I thought you couldn't call methods on primitive types in Java. It really needs to be `Double.isNan()` and not `double.IsNan()`, right?
Joren
2009-09-21 20:41:11
Joren, he's relying on autoboxing (double getting converted to Double by the compiler/runtime); new feature from 1.5 onwards. Little risk going this direction; going from Double to double creates risk of NullPointerExceptions.
M1EK
2009-09-21 21:01:09
I thought autoboxing only worked on using the double as an argument, adding it to a collection, and the like. Try declaring double x and then asking x to isNaN() - gives me a compiler error.
Carl
2009-09-22 02:23:20
Really, I suspect Andrew just missed the shift key typing the first "double".
Carl
2009-09-22 02:25:26
Yeah I think you're right.
M1EK
2009-09-22 17:11:36
+15
A:
Use the static Double.isNaN(double) method, or your Double's .isNaN() method.
Simply doing:
if (var == Double.NaN) {
...
}
is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.
Ben S
2009-09-21 20:11:21
+1
A:
You mentioned "test" in the question. This is how I would test with JUnit 4.x:
import static org.junit.Assert.*;
import org.junit.*;
import static java.lang.Double.*;
public class DoubleNanTests {
@Test
public void blahBlahBlahShouldCreateAnInvalidValue() {
double badDouble = NaN; // obtain double from unit under test
assertTrue("result should be an invalid value, but isn't", isNaN(badDouble) );
}
}
SingleShot
2009-09-21 20:19:41