The following code, which uses RoundingMode.HALF_EVEN,
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
4
6
5
7
RoundingMode.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.
RoundingMode.UP
RoundingMode.DOWN
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. , , , ( , , , ).
ROUND_HALF_EVEN
ROUND_HALF_UP