[英]Basic Java: Method to tell if a double is an integer
I'm a beginning programmer and I need a method that returns whether or not a double is an integer. 我是一个初学程序员,我需要一个方法来返回double是否为整数。 The problem occurs when the number is too big for an int to hold. 当数字太大而无法容纳int时,会出现问题。
Here's what I have: 这就是我所拥有的:
private static boolean isInteger(double n){
int ni = (int) n;
double nd = (double) ni;
if (nd==n)
return true;
return false;
}
Say I put in like 143215890634.0. 我说我像143215890634.0一样投入。 It will return false because the int can't store that many digits. 它将返回false,因为int无法存储那么多位数。
How can I allow the int(or another class) to store more digits or is there a better way to determine if a double is an int without comparing like this? 如何允许int(或另一个类)存储更多数字,或者有更好的方法来确定double是否为int而不进行比较?
Thanks in advance! 提前致谢!
Well long
holds more digits than int
. long
保持比int
更多的数字。 By the time you get outside the range of long
, all double
values are integers (and separated by more than 1). 当你超出long
的范围时, 所有 double
值都是整数(并且间隔超过1)。 So you could use something like: 所以你可以使用类似的东西:
private static boolean isInteger(double n) {
if (n > (double) Long.MAX_VALUE || n < (double) Long.MIN_VALUE) {
return true;
}
long asLong = (long) n;
return n == (double) asLong;
}
There are alternative approaches which would determine the bitwise representation, and check the exponent - but they'd be more complicated, at least to understand. 有其他方法可以确定按位表示,并检查指数 - 但它们会更复杂,至少要理解。
Note that checking for exact values in binary floating point is usually a bad idea. 请注意,检查二进制浮点中的精确值通常是个坏主意。 You might instead want to check how close the double
to the nearest integer, and have some sort of tolerance. 您可能希望检查double
与最接近的整数的接近程度,并具有某种容差。
try 尝试
boolean isInteger(double d) {
return d % 1 == 0;
}
Compare it to Integer.MAX_VALUE
. 将它与Integer.MAX_VALUE
进行比较。 If it is smaller - it will fit into integer assuming it has no fraction. 如果它更小 - 它将适合整数,假设它没有分数。
To store lager numbers you would have to use long
instead. 要存储较大的数字,您必须使用long
。 As for the comparison, you could maybe do num == Math.round(num)
instead. 至于比较,你可以改为num == Math.round(num)
。
I suppose, this would work even better than Math.round(), since it avoids type promotion: 我想,这比Math.round()更好用,因为它避免了类型提升:
double d1 = 143215890634.0, d2 = 143215890634.001;
System.out.println(d1 == Math.floor(d1));
System.out.println(d2 == Math.floor(d2));
This works, if with "integer" you don't mean actual type "int", but a "number without position after decimal point". 这是有效的,如果使用“整数”,则不是指实际类型“int”,而是“小数点后没有位置的数字”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.