【发布时间】:2011-01-07 13:49:04
【问题描述】:
我试图弄清楚如何将货币金额向上舍入到最接近的 5 美分。下面显示了我的预期结果
1.03 => 1.05
1.051 => 1.10
1.05 => 1.05
1.900001 => 1.10
我需要结果的精度为 2(如上所示)。
更新
按照下面的建议,我能做的最好的就是这个
BigDecimal amount = new BigDecimal(990.49)
// To round to the nearest .05, multiply by 20, round to the nearest integer, then divide by 20
def result = new BigDecimal(Math.ceil(amount.doubleValue() * 20) / 20)
result.setScale(2, RoundingMode.HALF_UP)
我不相信这是 100% 洁净的 - 我担心在转换为双打时可能会丢失精度。不过,这是迄今为止我想出的最好的方法,而且似乎可以工作。
【问题讨论】:
-
根据定义,由于四舍五入,您无论如何都会失去精度。我认为您不必担心精度损失。
-
顺便说一句,如果您担心精度,那么您应该使用 String 构造函数而不是 double 构造函数来创建 BigDecimals。
-
查看@marcolopes 的答案,了解如何在不使用
doubleValue()的情况下使用BigDecimal。 -
1:051 舍入到 1.05,而不是 1.10。
标签: java rounding bigdecimal