本文介绍了如何测试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
}
这会检查双精度值的舍入值是否与双精度值相同.
This checks if the rounded-down value of the double is the same as the double.
你的变量可以有一个 int 或 double 值,Math.floor(variable)
总是有一个 int 值,所以如果你的变量等于 Math.floor(variable)
code> 那么它必须有一个 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是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!