在Java中从double转换为int的精度下降 [英] Losing precision converting from double to int in Java

查看:481
本文介绍了在Java中从double转换为int的精度下降的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试测试以下代码,结果给了我434的n值,这是我没有预料到的结果,这种精度下降的原因是什么?

I tried to test the following code, and it gave me a 434 on n, the result which I did not anticipate, what's the reason for this loss of precision?

double f = 4.35;
int n =  (int) (100 * f); // n will be 434 - why?
n = (int) Math.round(100*f); // n will be 435

推荐答案

浮点数并不完美.它使用近似值.

Floating point isn't perfect. It uses approximated values.

尤其是,double不能代表所有数字.就像1/3不能用有限数量的数字精确地以十进制表示一样,4.35也不能用有限位数的二进制来精确表示.

In particular, doubles can not represent all numbers. Just like 1/3 can't be precisely represented in decimal using a finite number of digits, so too can't 4.35 be represented in binary with a finite number of bits.

所以我们得到了四舍五入的结果.与4.35接近 但不完全相等的值. 在这种情况下,它要小一些,所以当您将其乘以100时,您不会得到435,您会得到几乎435 ,这并不完全相同.

So we get rounded results. Values that are close to 4.35, but not quite equal. In this case, it's a bit smaller, so when you multiply it by 100, you don't get 435, you get almost 435, which is not quite the same.

强制转换为int时,将截断结果,因此434,999...变为434.

When you cast to int, you truncate the result, so 434,999... becomes just 434.

相反,当您使用Math.round时,会将434,999...转换为精确的435(可以精确表示 ).

In contrast, when you use Math.round, you convert 434,999... to exactly 435 (which can be represented precisely).

如果需要精确表示4.35,请查看Java BigDecimal 类型.

If precisely representing 4.35 is necessary, take a look at Java BigDecimal type.

这篇关于在Java中从double转换为int的精度下降的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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