How to handle rounding errors in Java's BigDecimal

為{幸葍}努か 提交于 2019-12-10 10:35:37

问题


I'm working with open source project (axil) that implements a scripting engine inside of java applications and I've hit a major stumbling block while trying to utilize BigDecimal's rounding. It seems that BigDecimal is converting my input to scientific notation and then applying my passed in precision to the coefficient of the SN representation of the number, rather than to its non-SN representation. For example:

new BigDecimal("-232454.5324").round(new MathContext(2, RoundingMode.HALF_UP)).toString()

produces a result of -2.3E+5. This presents two problems for me. First, I am expecting a result of -232454.5 (-2.324545E+5), so getting -230000 throws off any math that involves the result. And second, I am not expecting, nor can I find a way around, getting the results in SN (though I expect there is a formatting method out there that I haven't yet stumbled across).

Now due to the nature of the project, we can make very few expectations about what size/type of numbers will be getting passed into the round() method, so any solution needs to be highly modular. Does anyone have any suggestions? If it would be helpful here's a link to the google code issue report for this bug in the project. And here is a link to the project homepage.

Any help is very much appreciated.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/10883308/how-to-handle-rounding-errors-in-javas-bigdecimal

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