Java中双精度数转换为整数
在Java中,我想将双精度数转换为整数,我知道如果你这样做:
double x = 1.5;
int y = (int)x;
你会得到y=1。如果你这样做:
int y = (int)Math.round(x);
你可能会得到 2。但是,我想知道:由于整数的双精度表示有时看起来像 1.9999999998 或其他东西,是否有可能转换通过 Math.round() 创建的双精度仍然会导致截断的数字,而不是我们正在寻找的四舍五入的数字(即:代码中所示的 1 而不是 2)?
(是的,我的意思是这样的:是否有 x 的任何值,其中 y 将显示 x 的截断而不是舍入表示的结果?)
如果是这样:是否有将双精度数转换为四舍五入整数而不冒截断风险的更好方法?
想通了:Math.round(x) 返回的是 long,而不是 double。因此:Math.round() 不可能返回类似于 3.9999998 的数字。因此, int(Math.round()) 永远不需要截断任何内容并且始终有效。
In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
?否,
round()
始终会将双精度数舍入为正确的值值,然后,它将被转换为long
,这将截断所有小数位。但四舍五入后,不会剩下任何小数部分。以下是来自
的文档Math.round(双精度)
:No,
round()
will always round your double to the correct value, and then, it will be cast to anlong
which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.Here are the docs from
Math.round(double)
:对于数据类型
Double
到int
,您可以使用以下内容:这会截断(向下取整),并且不会舍入。使用风险自负。
For the datatype
Double
toint
, you can use the following:This truncates (floors), and does not round. Use at your own risk.
解决了我的目的。
Solved my purpose.