Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a double is an integer

Tags:

java

math

People also ask

Can a double be an integer?

The answer is no, because any integer which converts back and forth to the same value, actually represents the same integer value in double.

How do you check if a number is an integer?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


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.


public static boolean isInt(double d)
{
    return d == (int) d;
}

Try this way,

public static boolean isInteger(double number){
    return Math.ceil(number) == Math.floor(number); 
}

for example:

Math.ceil(12.9) = 13; Math.floor(12.9) = 12;

hence 12.9 is not integer, nevertheless

 Math.ceil(12.0) = 12; Math.floor(12.0) =12; 

hence 12.0 is integer