Skip to content
Advertisement

How to test if a double is an integer

Is it possible to do this?

double variable;
variable = 5;
/* the below should return true, since 5 is an int. 
if variable were to equal 5.7, then it would return false. */
if(variable == int) {
    //do stuff
}

I know the code probably doesn’t go anything like that, but how does it go?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement