Search code examples
javaroundingcurrencybigdecimal

BigDecimal setScale using rounding mode half even not working


Someone please tell me the mistake I did:

I have the number: 225.0453 which internally is saved with 4 digits. This is a USD currency number that i want pretty print for displaying. I use RoundingMode.HALF_EVEN

As USD uses 2 fraction digits the half even rounded number should be $225.04. But i get $225.05.

This is my code (i changed it to create a MWE):

@Override
public String toString() {
    Currency cur = Currency.getInstance("USD");
    BigDecimal result = new BigDecimal("225.0453");
    result = result.setScale(cur.getDefaultFractionDigits(),RoundingMode.HALF_EVEN);
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    nf.setCurrency(cur);
    nf.setMaximumFractionDigits(cur.getDefaultFractionDigits());
    return nf.format(result.doubleValue());
}

In addition i will also be greatful for a better solution as this seems not quite right. (I tried nf.setRoundingMode but that did not work at all)


Solution

  • The RoundingMode HALF_EVEN rounds toward the even neighbor only when the value is equidistant between possible rounding targets.

    Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

    This means that it would have rounded down if the amount was 225.045, the equidistant value. But because your amount of 225.0453 was greater than the equidistant value, it will still round up.