在 Java 中,我想将 double 转换为整数,我知道你是否这样做:
double x = 1.5;
int y = (int)x;
你得到 y=1。如果你这样做:
int y = (int)Math.round(x);
您可能会得到 2。但是,我想知道:由于整数的双重表示有时看起来像 1.9999999998 或其他东西,是否有可能通过 Math.round() 创建的双重表示仍会导致截断数字,而不是我们正在寻找的四舍五入的数字(即:代码中的 1 而不是 2)?
(是的,我的意思是这样的:x 是否有 any 值,其中 y 将显示一个截断而不是舍入表示 x 的结果?)
如果是这样:有没有更好的方法可以将 double 整数转换为舍入整数而不会有截断的风险?
想出一些东西:Math.round(x) 返回一个 long,而不是 double。因此:Math.round() 不可能返回一个看起来像 3.9999998 的数字。因此,int(Math.round()) 永远不需要截断任何内容,并且始终有效。
最佳答案
is there a possibility that casting a double created via
Math.round()
will still result in a truncated down number
不,round()
将始终将您的 double 舍入为正确的值,然后将其转换为 long
将截断任何小数位。但四舍五入后,就不会剩下任何小数部分了。
这里是来自 Math.round(double)
的文档:
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
关于java - 在Java中将double转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6468730/