如何测试double是否为整数 [英] How to test if a double is an integer

查看:137
本文介绍了如何测试double是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以这样做?

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?

推荐答案

if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // integer type
}

这会检查double的向下舍入值是否与double。

This checks if the rounded-down value of the double is the same as the double.

你的变量可以有一个int或double值, Math.floor(变量)总是有一个int value,所以如果你的变量等于 Math.floor(变量)那么它必须有一个int值。

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.

这篇关于如何测试double是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆