To round a number I use the following code:
public static roundBd(BigDecimal bd){
BigDecimal result1 = bd.setScale(0, RoundingMode.HALF_UP);
return result1;
}
- Input 1.50 –> Output 2
- Input 1.499 –> Output 1
The first result is ok for me, but the second is not what I expected.
Even for 1.499 I’d like to have in output 2. (In details: first I’d like to round 1.499 to 1.50 then to 1.5 and finally to 2)
But….
BigDecimal bd = new BigDecimal("1.499"); // I'd like to round it to 2
BigDecimal result1 = bd.setScale(2, RoundingMode.HALF_UP); // result1 == 1.50
BigDecimal result2 = bd.setScale(1, RoundingMode.HALF_UP); // result2 == 1.5
BigDecimal result3 = bd.setScale(0, RoundingMode.HALF_UP); // result3 == 1
That’s not the way rounding works. HALF_UP means that if a number is exactly in the middle between the 2 closest available values (depending on the scale), it will be rounded up. Anything else is rounded to the closest value.
Extract from the javadoc:
To get to the behaviour you require, you could round successively although I’m not sure why you want such a behaviour: