Search code examples
javabigdecimal

BigDecimal division, rounding and sums


I am working with a BigDecimal value that represents a currency amount. I need to split this amount into 6 rates with the first 5 rates being rounded up to 5, the 6th rate will be the rest.

BigDecimal numberOfRates = new BigDecimal("6");
BigDecimal currencyAmount = new BigDecimal("650.30");
BigDecimal rate = currencyAmount.divide(numberOfRates);
rate = //rate rounded up to closest multiple of 5
BigDecimal lastRate = currencyAmount.subtract(rate.multiply(new BigDecimal("5"));

My 2 questions are:

  • How do I round to the closest multiple of 5 (or any other int)?
  • Will the 6 rates summed up always give the original currencyAmount or are there issues with precision due to the division?

(This is a simplified example, I do realize that the last rate could be negative with this setup.)

* Updated Question *

Expected result with the example is:

  • Rates 1-5: 110.00
  • Rate 6: 100.30 And in this case: 5*110.00 + 100.30 = 650.30

By using the indicated approaches will it always be the case that the sum of all rates equals the initial amount?


Solution

  • Use the standard approach of divide, round, multiply

    private static BigDecimal round(BigDecimal input, int multiple) {
        return input.divide(new BigDecimal(multiple))
                .setScale(0, RoundingMode.CEILING)
                .multiply(new BigDecimal(multiple));
    }
    
    for (double i = 0; i < 10; i += 0.9) {
        System.out.println(String.format("%.1f => %s", i, round(new BigDecimal(i), 5)));
    }
    

    Output

    0.0 => 0
    0.9 => 5
    1.8 => 5
    2.7 => 5
    3.6 => 5
    4.5 => 5
    5.4 => 10
    6.3 => 10
    7.2 => 10
    8.1 => 10
    9.0 => 10
    9.9 => 10