java舍入误差规律,安卓:java的舍入误差。不明白为什么?

Can anybody explain why on Earth these "same" expressions returns different values?

(new BigDecimal(String.valueOf(131.7d))).multiply(new BigDecimal(String.valueOf(0.95d))).doubleValue() = 125.115

(new BigDecimal( 131.7d )).multiply(new BigDecimal( 0.95d )).doubleValue() = 125.11499999999998

What BigDecimal is doing different between them?

解决方案

If you read the API documentation, you will find taht String.valueOf(dobule) uses Double.toString(double) to format the value. It's perhaps not obvious, but Double.toString(double) rounds the value, before formatting it as a string:

How many digits must be printed for the fractional part of m or a?

There must be at least one digit to represent the fractional part, and

beyond that as many, but only as many, more digits as are needed to

uniquely distinguish the argument value from adjacent values of type

double. That is, suppose that x is the exact mathematical value

represented by the decimal representation produced by this method for

a finite nonzero argument d. Then d must be the double value nearest

to x; or if two double values are equally close to x, then d must be

one of them and the least significant bit of the significand of d must

be 0.

The result of this is that String.valueOf(131.7d) will return the string "131.7" even if the exact value of the argument is 131.69999999999998863131622783839702606201171875. The reason for this is that decimal fractions cannot always be represented exactly using binary fractions (as used with floats and doubles).

So, new new BigDecimal(String.valueOf(131.7)) will create a BigDecimal with the exact value 131.7. new BigDecimal(131.7) will create a BigDecimal with the exact value 131.69999999999998863131622783839702606201171875.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值