Java--About ROUND_HALF_DOEN rounding

When learning BigDecimal (precision calculation of floating point numbers), knocked on this string of code:
BigDecimal c = new BigDecimal ("18.8452"). SetScale (2, BigDecimal.ROUND_HALF_DOWN);

ROUND_HALF_DOWN is rounded off, two decimal places are reserved, the originally printed value should be 18.84, but the result is printed 18.85

It turned out that because of rounding, the discarded value must be exactly equal to 5 or less than 5, for example, 18.8452, two decimal places are retained, the discarded value is 0.0052, which is greater than 0.0050, so it will still be rounded up. The code is as follows :

//BigDecimal.ROUND_HALF_UP表示四舍五入
//BigDecimal.ROUND_HALF_DOWN也是五舍六入
//BigDecimal.ROUND_UP表示进位处理(就是直接加1)
//BigDecimal.ROUND_DOWN表示直接去掉尾数。
BigDecimal a = new BigDecimal("18.8450").setScale(2, BigDecimal.ROUND_HALF_DOWN);
BigDecimal c = new BigDecimal("18.8452").setScale(2, BigDecimal.ROUND_HALF_DOWN);
System.out.println(a);
System.out.println(c);

a prints 18.84
c prints 18.85

Published 6 original articles · liked 0 · visits 85

Guess you like

Origin blog.csdn.net/ShaoWeiY/article/details/104703499