如何处理Java的BigDecimal中的舍入错误 [英] How to handle rounding errors in Java's BigDecimal

查看:174
本文介绍了如何处理Java的BigDecimal中的舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用在java应用程序中实现脚本引擎的开源项目(axil),并且在尝试利用BigDecimal的舍入时遇到了一个主要的障碍。似乎BigDecimal正在将我的输入转换为科学记数法,然后将我传入的精度应用于数字的SN表示系数,而不是其非SN表示。例如:

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()

产生 -2.3E + 5 的结果。这给我带来了两个问题。首先,我期待 -232454.5 -2.324545E + 5 )的结果,所以得到 -230000 抛弃任何涉及结果的数学运算。第二,我没想到,也无法找到解决办法,将结果记录在SN中(虽然我希望有一种格式化方法,我还没有偶然发现)。

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).

现在由于项目的性质,我们很少期望将数量的大小/类型传递给round()方法,因此任何解决方案都需要高度模块化。有没有人有什么建议? 如果有帮助,请点击此处链接关于项目中此错误的Google代码问题报告。 这里是项目主页的链接。

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.

非常感谢任何帮助。

推荐答案

不要使用round方法,而是使用setScale,其中argument是小数位数:

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

另请注意,setScale返回一个新的BigDecimal实例,它不会更改当前实例的比例。

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

这篇关于如何处理Java的BigDecimal中的舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆