Why RoundingMode?
Because 10/3 => ArithmeticException
- ptifall: new BigDecimal("10").divide(new BigDecimal("3"))
- => ArithmeticException (result is 3.3333.....333)
- solution [use RoundingMode]: new BigDecimal("10").divide(new BigDecimal("3"), RoundingMode.HALF_UP)
- => OK
Why Precision?
Because 3/1000 == 0
- ptifall: new BigDecimal("3").divide(new BigDecimal("10000"), RoundingMode.HALF_UP)
- => 0.0003 => 0
- solution [use Precision (Presision+RoundingMode = MathContext)]:
- int precision = 10;
- public static MathContext MATH_CONTEXT = new MathContext(precision, RoundingMode.HALF_UP);
- new BigDecimal("3").divide(new BigDecimal("10000"), MATH_CONTEXT)
Therefore when deviding BigDecimals always use MathContext (i.e. RoundingMode and Precision).
No comments:
Post a Comment