Double.intValue()如何工作? [英] How does Double.intValue() work?

查看:116
本文介绍了Double.intValue()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

Double dbl = 254.9999999999999;
Integer integ = dbl.intValue();
System.out.println(integ);

显示254,但一个9更多

shows 254, but one "9" more

Double dbl = 254.99999999999999;
Integer integ = dbl.intValue();
System.out.println(integ);

它已经是255 ..
为什么?

and it is already 255.. Why?

推荐答案

要知道双重的确切值,可以使用BigDecimal:

To know the exact value of your double, you can use a BigDecimal:

System.out.println(new BigDecimal(254.9999999999999));
System.out.println(new BigDecimal(254.99999999999999));

打印:

254.9999999999998863131622783839702606201171875
255

所以这只是因为(限制)双精度...

So this is simply due to (limitations of) double precision...

这篇关于Double.intValue()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆