开发者

Strange rounding behaviour with BigDecimal?

开发者 https://www.devze.com 2023-04-06 02:58 出处:网络
What would be printed to console and why? 1. BigDecimal BigDecimalNum = new BigDecimal(\"0.0774\"开发者_运维知识库);

What would be printed to console and why?

1.

BigDecimal BigDecimalNum = new BigDecimal("0.0774"开发者_运维知识库);
System.out.println(BigDecimalNum.doubleValue() * 100.00);

2.

BigDecimal BigDecimalNum2 = new BigDecimal("0.0774");   
System.out.println(BigDecimalNum2.multiply(new BigDecimal("100.00")));


The results on my machine are:

7.739999999999999
7.740000

This doesn't surprise me at all. In the second case we're dealing entirely with BigDecimal, and always multiplying - there's no reason for anything to go wrong.

In the first case you're converting the BigDecimal to a double, so your code is effectively

double d = 0.0774;
System.out.println(d * 100.0);

The value 0.0774 can't be exactly represented as a double, hence the discrepancy.

This has nothing to do with BigDecimal, and everything to do with double. You should almost never be converting between BigDecimal and double though - the kind of values which are appropriate for use in BigDecimal are almost always inappropriate to represent as double values.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号