Rounding mode with BigDecimal in Java

The following code, which uses RoundingMode.HALF_EVEN,

BigDecimal value1 = new BigDecimal("4.5");
value1=value1.setScale(0, RoundingMode.HALF_EVEN);

BigDecimal value2 = new BigDecimal("6.5");
value2=value2.setScale(0, RoundingMode.HALF_EVEN);

System.out.println(value1+"\n"+value2);

displays 4and 6accordingly. I think that it should display 5and 7accordingly, because the figure on the left of the discarded fractional part (which in this case is equal to 5) is odd . In this case, it performsRoundingMode.HALF_UP

And in the case RoundingMode.HALF_UP, it RoundingMode.UPis executed when the discarded fractional part is> = 0.5 (this is true), otherwise it is executed RoundingMode.DOWN.

+5
source share
1 answer

The behavior is well described in Javadoc :

" " , , , .

, 4.5, 4 5, :

BigDecimal value1 = new BigDecimal("4.5").setScale(RoundingMode.ROUND_HALF_EVEN);

, , , 4 5? , , 4.5 , . , , . ROUND_HALF_EVEN. , ROUND_HALF_UP, 5, 4. , , , ( , , , ).

+13

All Articles