Well long
holds more digits than int
. By the time you get outside the range of long
, all double
values are integers (and separated by more than 1). So you could use something like:
private static boolean isInteger(double n) {
if (n > (double) Long.MAX_VALUE || n < (double) Long.MIN_VALUE) {
return true;
}
long asLong = (long) n;
return n == (double) asLong;
}
There are alternative approaches which would determine the bitwise representation, and check the exponent - but they'd be more complicated, at least to understand.
Note that checking for exact values in binary floating point is usually a bad idea. You might instead want to check how close the double
to the nearest integer, and have some sort of tolerance.