用于金融计算和非终止计算的 Bigdecimal
我确信这是一个简单的问题,但我无法决定必须做什么。就是这样:假设我们遵循使用 BigDecimal 进行财务计算的“最佳实践”,那么如何处理抛出异常的内容(计算)?
举个例子:假设,我必须在“n”个不同实体之间分配“用户金额”来投资债券。现在考虑用户提交 100 美元用于投资并分配给 3 个债券的情况。等效的代码如下所示:
public static void main(String[] args) throws Exception {
BigDecimal bd1 = new BigDecimal("100.0");
BigDecimal bd2 = new BigDecimal("3");
System.out.println(bd1.divide(bd2));
}
但众所周知,这个特定的代码片段会抛出 ArithmeticException ,因为除法是非终止的。在计算过程中使用无限精度数据类型时,如何在代码中处理这种情况?
TIA,
sasuke
更新:鉴于RoundingMode将有助于解决这个问题,下一个问题是,为什么100.0/3不是33.33而是33.3? 33.33 不是一个“更”准确的答案吗,就像您期望的 33 美分而不是 30 一样?有什么办法可以调整这个吗?
I'm sure this would be a simple question to answer but I can't for the life of me decide what has to be done. So here's it: assuming we follow the "best practice" of using BigDecimal
for financial calculations, how can one handle stuff (computations) which throw an exception?
As as example: suppose, I have to split a "user amount" for investing in bonds between "n" different entities. Now consider the case of user submitting $100 for investing to be split between 3 bonds. The equivalent code would look like:
public static void main(String[] args) throws Exception {
BigDecimal bd1 = new BigDecimal("100.0");
BigDecimal bd2 = new BigDecimal("3");
System.out.println(bd1.divide(bd2));
}
But as we all know, this particular code snippet would throw an ArithmeticException
since the division is non-terminating. How does one handle such scenarios in their code when using infinite precision data types during computations?
TIA,
sasuke
UPDATE: Given that RoundingMode
would help remedy this issue, the next question is, why is 100.0/3 not 33.33 instead of 33.3? Wouldn't 33.33 be a "more" accurate answer as in you expect 33 cents instead of 30? Is there any way wherein I can tweak this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是使用
BigDecimal.divide()
方法指定RoundingMode
。例如,以下使用舍入模式 半偶数 或银行四舍五入(但根据要求半数或其他舍入模式之一可能更合适),并将四舍五入到小数点后两位:
The answer is to use one of the
BigDecimal.divide()
methods which specify aRoundingMode
.For example, the following uses the rounding mode half even or bankers rounding (but half up or one of the other rounding modes may be more appropriate depending on requirements) and will round to 2 decimal places:
divide
有一个采用舍入模式的重载。您需要选择一个。我相信“半偶”是货币计算中最常用的一种。divide
has an overload that takes a rounding mode. You need to choose one. I believe "half even" is the most commonly used one for monetary calculations.这是一个例子,具体取决于您想要的舍入。
It's an exemple, depending on the rounding you want.