javadouble转int四舍五入_在Java中从double转换为int的精度下降

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.

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.

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.

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值