tags:

views:

245

answers:

4

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
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
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
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
Really, I suspect Andrew just missed the shift key typing the first "double".
Carl
Yeah I think you're right.
M1EK
+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
Another way to do this would be v != v. Only NaN compares false with itself. Don't do that though, isNaN is a million times better. :)
Joren
@Joren: lol, Thumbs up for obfuscated Java!
Ben S
+1  A: 

Check the Javadoc for the Double API.

Chris Arguin
+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