This problem arises from the fact that some floating-point methods and operations produce Infinity or NaN as results instead of throwing an exception.
The solution to checking whether the given float/double is a finite floating-point value relies on the following conditions—the absolute value of the given float/double value must not exceed the largest positive finite value of the float/double type:
// for float
Math.abs(f) <= Float.MAX_VALUE;
// for double
Math.abs(d) <= Double.MAX_VALUE
Starting with Java 8, the preceding conditions were exposed via two dedicated flag-methods, Float.isFinite() and Double.isFinite(). Therefore, the following examples are valid test cases for finite floating-point values:
Float f1 = 4.5f;
boolean f1f = Float.isFinite(f1); // f1 = 4.5, is finite
Float f2 = f1 / 0;
boolean f2f = Float.isFinite(f2); // f2 = Infinity, is not finite
Float f3 = 0f / 0f;
boolean f3f = Float.isFinite(f3); // f3 = NaN, is not finite
Double d1 = 0.000333411333d;
boolean d1f = Double.isFinite(d1); // d1 = 3.33411333E-4,is finite
Double d2 = d1 / 0;
boolean d2f = Double.isFinite(d2); // d2 = Infinity, is not finite
Double d3 = Double.POSITIVE_INFINITY * 0;
boolean d3f = Double.isFinite(d3); // d3 = NaN, is not finite
These methods are handy in conditions such as the following:
if (Float.isFinite(d1)) {
// do a computation with d1 finite floating-point value
} else {
// d1 cannot enter in further computations
}