How to test if a double is an integer
public static boolean isInt(double d)
{
return d == (int) d;
}
Or you could use the modulo operator:
(d % 1) == 0
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integer type
}
This checks if the rounded-down value of the double is the same as the double.
Your variable could have an int or double value and Math.floor(variable)
always has an int value, so if your variable is equal to Math.floor(variable)
then it must have an int value.
This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.
Guava: DoubleMath.isMathematicalInteger
. (Disclosure: I wrote it.) Or, if you aren't already importing Guava, x == Math.rint(x)
is the fastest way to do it; rint
is measurably faster than floor
or ceil
.