Search code examples
javabigdecimal

Understand mathematical operations using BigDecimal in Java


Using Java (JDK 1.8.0_66 and JDK 1.8.0_181) and its built-in BigDecimal class while performing the following operations:

    BigDecimal res = new BigDecimal("290");
    BigDecimal sub = new BigDecimal("22");
    sub = sub.subtract(new BigDecimal("7"));
    sub = sub.subtract(new BigDecimal("4"));
    res = res.divide(new BigDecimal("22"), 2, RoundingMode.HALF_EVEN);
    res = res.multiply(sub);
    res = res.setScale(2, RoundingMode.HALF_EVEN);

yields the result of 144.98 while expected is 145.

Why does that happen? I have tried local and an online compiler. Is setting the scale happening too late? And how can I get a more accurate calculation?

This formula is used to represent monetary value calculations.


Solution

  • The correct answer is 144.98. You compute 290/22 to a presicion of two decimals. The result is 13.18. And 13.18*11 is 144.98

    If your computation is "if I were to pay $145 in 11 equal installments, how big should the installments be" you would have to take the difference of 2 cents and add them to the installments.