How to handle rounding errors in Java's BigDecimal

僤鯓⒐⒋嵵緔 提交于 2019-12-06 05:05:05

Don't use the round method , use setScale instead, where argument is number of decimals:

BigDecimal bd = new BigDecimal("-232454.5324").setScale(1,
                RoundingMode.HALF_UP);
String string = bd.toPlainString();
System.out.println(string); // prints -232454.5

Also note that setScale returns a new BigDecimal instance, it doesn't change the scale of the current instance.

I would do it like that:

BigDecimal number = new BigDecimal("22.2222").setScale(0, RoundingMode.UP);

if (number.intValue() % 2 != 0) {
    number = number.add(BigDecimal.ONE);
}

System.out.println(number); // => 24

A MathContext takes a precision, which is the total number of significant digits -- before and after the decimal place -- in the result. BigDecimal's logic is correct here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!