Search code examples
javamathroundingbigdecimal

BigDecimal HALF_UP rounding issue


I am trying to round 0.14049 using scale=3 and HALF_UP rounding mode and hoping to see rounded value = 0.141 but getting 0.140 instead.

As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

Is that a bug in BigDecimal setScale method or my expectation of Rounding is wrong. How can I get rounded values similar to 0.141 and not 0.140?

BigDecimal bd=new BigDecimal("0.14049");
BigDecimal normalizedField = field.setScale(3, RoundingMode.HALF_UP);
System.out.println(normalizedField);
// Output = 0.140

Solution

  • As per my understanding the last decimal digit 9 should round up the 4 to 5 and that should in-turn round up 0 to 1 when using scale 3 and i should see 0.141.

    This understanding is incorrect. Rounding is not an iterative process. Only the first digit after the scale position is considered, not the whole chain of digits. In your case, the digit is 4, so it gets converted down to zero.