If you have a double/float/floating point number and want to see if it’s an integer.
public boolean isDoubleInt(double d)
{
//select a "tolerance range" for being an integer
double TOLERANCE = 1E-5;
//do not use (int)d, due to weird floating point conversions!
return Math.abs(Math.floor(d) - d) < TOLERANCE;
}
If you have a string and want to see if it’s an integer. Preferably, don’t throw out the Integer.valueOf()
result:
public boolean isStringInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
If you want to see if something is an Integer object (and hence wraps an int
):
public boolean isObjectInteger(Object o)
{
return o instanceof Integer;
}