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:
(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:
By using the indicated approaches will it always be the case that the sum of all rates equals the initial amount?
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