问题描述
我尝试将两个 BigDecimal
值乘以乘以
方法,如下所示,
I try to multiply two BigDecimal
Values with multiply
methods as follows,
BigDecimal dur = BigDecimal.valueOf(60/1.1);
BigDecimal bal = BigDecimal.valueOf(1.1);
BigDecimal ans = dur.multiply(bal);
System.out.println("Ans:"+ans);
我除了 60
。但我得到了它,
I am excepting ans as 60
. But i got it as,
Ans:59.999999999999994
为什么会这样,我们如何解决呢。
Why this comming and how can we resolve it.
推荐答案
问题是你有一个不能在 double
中表示的值,但也不能在BigDecimal中表示,所以你必须应用合理的舍入来获得预期的解决方案。
The problem is you have a value which can't be represented in double
but nor can it be represented in BigDecimal so you have to apply reasonable rounding to get the expected solution.
double d = 60 / 1.1 * 1.1;
System.out.println("double without rounding: " + d);
System.out.printf("double With rounding %.2f%n", d);
BigDecimal bd = BigDecimal.valueOf(60).divide(BigDecimal.valueOf(1.1), 9, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(1.1));
System.out.println("BigDecimal without rounding: " + bd);
System.out.printf("BigDecimal with rounding %.2f%n", bd);
// or
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("BigDecimal with rounding: " + bd);
打印
double without rounding: 60.0
double With rounding 60.00
BigDecimal without rounding: 59.9999999995
BigDecimal with rounding 60.00
BigDecimal with rounding: 60.00
注意: double
恰好为这些值进行正确舍入并给出正确的答案。但是,选择一个不同的组合,它将是不正确的。例如 54.545454545454545 * 1.1 => 60.00000000000001
Note: double
happens to round correctly for these values and gives the right answer. However, pick a different combination and it will be incorrect. e.g. 54.545454545454545 * 1.1 => 60.00000000000001
这篇关于BigDecimal乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!