How to check if floating point is NaN in Java

2 Answers

0 votes
public class Program {
    public static void main(String[] args) {
        float value = 0.0f / 0.0f; // Produces NaN
        
        if (Float.isNaN(value)) {
            System.out.println("The value is NaN.");
        } else {
            System.out.println("The value is not NaN.");
        }
    }
}



/*
run:

The value is NaN.

*/

 



answered Aug 3, 2025 by avibootz
0 votes
public class Program {
    public static void main(String[] args) {
        double value = Math.sqrt(-1); // Produces NaN

        if (Double.isNaN(value)) {
            System.out.println("The value is NaN.");
        } else {
            System.out.println("The value is not NaN.");
        }
    }
}



/*
run:

The value is NaN.

*/

 



answered Aug 3, 2025 by avibootz
...