Check if a double is equal to NaN in Java
This post will discuss how to check if double is equal to NaN in Java.
A Not-a-Number (NaN) value can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic. In Java, you can’t compare NaN with a float or a double using the == operator, as per the IEEE 754 floating-point standard.
1. Using isNaN() method
The Double class provides a static method isNaN(double) which returns true if the specified number is a NaN, false otherwise.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { double doubleValue = Double.NaN; if (Double.isNaN(doubleValue)) { System.out.println("Not a Number"); } } } |
Output:
Not a Number
Depending on the variable type, you can either use the Double.isNaN(double) or Float.isNaN(float) method.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { float floatValue = Float.NaN; if (Float.isNaN(floatValue)) { System.out.println("Not a Number"); } } } |
Output:
Not a Number
If you’re using the Double object instead of a primitive double, you can directly call the isNaN() method on it.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { Double doubleValue = Double.NaN; if (doubleValue.isNaN()) { System.out.println("Not a Number"); } } } |
Output:
Not a Number
2. Using != operator
Another approach is to compare the double value with itself using the != operator. If the value is NaN, it returns true, since only NaN evaluates false with itself. This approach is used by the isNaN() method, but it lacks readability and might cause confusion for other programmers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Main { static public boolean isNaN(double d) { return d != d; } public static void main(String[] args) { double doubleValue = Double.NaN; if (isNaN(doubleValue)) { System.out.println("Not a Number"); } } } |
Output:
Not a Number
3. Using Double.isFinite() method
Finally, you can use the Double.isFinite() method that returns true for finite floating-point value and false for NaN and infinity. The following code demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { double doubleValue = Double.NaN; if (!Double.isFinite(doubleValue)) { System.out.println("Not a Number"); } } } |
Output:
Not a Number
Note that the code returns true not just for Double.NaN, but for Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY as well.
That’s all about checking if double is equal to NaN in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)