Understanding round half even?

前端 未结 2 606
耶瑟儿~
耶瑟儿~ 2021-01-22 18:26

When i print

(new BigDecimal(5) * new BigDecimal(0.049))​

It gives

0.24500000000000000943689570931383059360086917877197265625
<         


        
2条回答
  •  余生分开走
    2021-01-22 19:22

    int java.math.BigDecimal.ROUND_HALF_EVEN : 6 [0x6]

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

    0.24500000000000000943689570931383059360086917877197265625 is closer to 0.25 than to 0.24. The even neighbour is only chosen is the distance from both neighbors is equal (i.e. if you were trying to round 0.245).

    BigDecimal bd = new BigDecimal("0.245").setScale(2, BigDecimal.ROUND_HALF_EVEN);
    System.out.println (bd);
    

    will print 0.24.

提交回复
热议问题