A floating point value is an integer if it equals its truncation:
public boolean isInteger(double x)
{
return x == (int) x;
}
However, remember that floating-point numbers often have rounding issues that cause strange results. For example, you might be doing some math and end up with a value of (for example) 1.00000000001 when the correct answer without rounding errors is 1. If you pass such a number to isInteger()
above, it'll return false
. If this is a concern, you need to do a "close enough" check, using a tolerance parameter.
Maybe something like this, although I imagine it could be improved:
// test if x is "closer than epsilon" to an integer
// typical value for epsilon might be, say, 0.000001
public boolean isInteger(double x, double epsilon)
{
double delta = Math.Abs(x - (int) x);
delta -= (int) delta;
return delta < epsilon;
}