ArithmeticException thrown during BigDecimal.divide

后端 未结 9 689
渐次进展
渐次进展 2020-11-30 08:41

I thought java.math.BigDecimal is supposed to be The Answer™ to the need of performing infinite precision arithmetic with decimal numbers.

Consider the followi

9条回答
  •  生来不讨喜
    2020-11-30 09:16

    If you want to work with decimals, not rational numbers, and you need exact arithmetics before the final rounding (rounding to cents or something), here's a little trick.

    You can always manipulate your formulas so that there's only one final division. That way you won't lose precision during calculations and you'll always get the correctly rounded result. For instance

    a/b + c
    

    equals

    (a + bc) / b.
    

提交回复
热议问题