I have the following requirement to round amounts:
1.2448 -> 1.25
3.349 -> 3.35
0.474 -> 0.47
I have tried all the possible modes of the BigDecimal.setScale(2, RoundingMode.) method, without any success. Here is the result:
UP: 1.25, 3.35, 0.48
HALF_UP: 1.24, 3.35, 0.47
CEILING: 1.25, 3.35, 0.48
FLOOR: 1.24, 3.34, 0.47
DOWN: 1.24, 3.34, 0.47
HALF_DOWN: 1.24, 3.35, 0.47
HALF_EVEN: 1.24, 3.35, 0.47
I have also tried to use BigDecimal.round(), with not good result neither.
How can I round the amounts in the required way ?
Edit:
Why do I actually need to round in this seemingly bizarre way?
In a new software we are developing, we need to reproduce the rounding behavior or a legacy software (which is the way business wants rounding to be done)
Solution:
I absolutely want to stay with BigDecimals for all my calculations.
So, at the end I came up with this simple function to do the "progressive" rounding:
public static BigDecimal roundAmount(BigDecimal amount) {
for (int i = amount.scale(); i >= 2; i--) {
amount = amount.setScale(i, RoundingMode.HALF_UP);
}
return amount;
}