是否有可能做到这一点?
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
}
Run Code Online (Sandbox Code Playgroud)
我知道代码可能不会去这样的事情,但怎么也去了?
Sko*_*eet 196
或者您可以使用模运算符:
(d % 1) == 0
max*_*hud 133
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integer type
}
Run Code Online (Sandbox Code Playgroud)
这将检查double的向下舍入值是否与double相同.
你的变量可以有一个int或double值,并且Math.floor(variable)总是有一个int值,所以如果你的变量等于Math.floor(variable)那么它必须有一个int值.
如果变量的值是无穷大或负无穷大,这也不起作用,因此在条件中添加"只要变量不是无限的".
Lou*_*man 81
番石榴:DoubleMath.isMathematicalInteger.(披露:我写过它.)或者,如果你还没有进口番石榴,x == Math.rint(x)那么这是最快的方法; rint比floor或者快得多ceil.
Eng*_*uad 19
public static boolean isInt(double d)
{
return d == (int) d;
}
Run Code Online (Sandbox Code Playgroud)
试试这个方法
public static boolean isInteger(double number){
return Math.ceil(number) == Math.floor(number);
}
Run Code Online (Sandbox Code Playgroud)
例如:
Math.ceil(12.9) = 13; Math.floor(12.9) = 12;
Run Code Online (Sandbox Code Playgroud)
因此12.9是未整数,不过
Math.ceil(12.0) = 12; Math.floor(12.0) =12;
Run Code Online (Sandbox Code Playgroud)
因此12.0是整数
这是一个很好的解决方案:
if (variable == (int)variable) {
//logic
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114058 次 |
| 最近记录: |