I need to round numbers to two decimal places:
1.1245 → 1.13 1.1235 → 1.12
I have spent the last two days scouring StackOverflow, and I have been unable to get any solution I have found to work at all:
- What rounding method should you use in Java for money?
- Rounding BigDecimal to always have two decimal places
- Using DecimalFormat
They all seem to simply truncate the number at the third decimal place, then round it from there, which is not what I am trying to do. I am trying to start at the place furthest to the right, and then begin rounding appropriately; 5-9 goes up, 0-4 has no effect and is dropped.
Here is the current code I am working with:
BigDecimal a = new BigDecimal("1.1245");
double b = Math.round(a.doubleValue() * 100) / 100;
System.out.print(a.setScale(2, BigDecimal.ROUND_HALF_EVEN) + " : "
+ a.setScale(2, BigDecimal.ROUND_HALF_UP) + " : "
+ b);
And here is the output straight from the console:
The problem here is that I am expecting 1.13 to be the result in all of the above cases, as though the following process is followed:
1.1245 → 1.125 → 1.13
1.1235 → 1.124 → 1.12