java - 在Java中将double转换为整数

标签 java casting double rounding

在 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/

相关文章:

generics - F# 中算术转换为泛型类型

c++ - 为什么我不能 static_cast 继承树下的模板化对象?

c# - 如何将二进制字符串转换为 float 或 double ?

java - 创建具有相同类型参数的类型变量

java - 在线更新客户名单

c++ - 无法从 vector<T> 转换为 T

Java 似乎没有正确比较 double

VBA:Variant/Double 和 Double 之间的区别

java - 在 JBOSS 7 中使用 CXF WS 实现 X509 时出现的问题

java - 匹配 3 个或更多连续连续字符和连续相同字符的正则表达式