How to test if a double is an integer

2019-01-02 15:01发布

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?

标签: java math
12条回答
其实,你不懂
2楼-- · 2019-01-02 15:38

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

查看更多
荒废的爱情
3楼-- · 2019-01-02 15:38

Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:

if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
    // no decimal places
} else {
    // decimal places
}

Remainder(BigDecimal) returns a BigDecimal whose value is (this % divisor). If this one's equal to zero, we know there is no floating point.

查看更多
倾城一夜雪
4楼-- · 2019-01-02 15:38

Here's a solution:

float var = Your_Value;
if ((var - Math.floor(var)) == 0.0f)
{
    // var is an integer, so do stuff
}
查看更多
人气声优
5楼-- · 2019-01-02 15:39

Consider:

Double.isFinite (value) && Double.compare (value, StrictMath.rint (value)) == 0

This sticks to core Java and avoids an equality comparison between floating point values (==) which is consdered bad. The isFinite() is necessary as rint() will pass-through infinity values.

查看更多
初与友歌
6楼-- · 2019-01-02 15:40

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()
查看更多
刘海飞了
7楼-- · 2019-01-02 15:41

you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:

public final double testRange = 0.2;

public static boolean doubleIsInteger(double d){
    int i = (int)d;
    double abs = Math.abs(d-i);
    return abs <= testRange;
}

If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.

查看更多
登录 后发表回答