BigDecimal setScale 使用四舍五入模式一半甚至不工作
BigDecimal setScale using rounding mode half even not working
有人请告诉我我犯的错误:
我有号码:225.0453,内部保存为 4 位数字。这是一个美元货币数字,我想要漂亮的印刷品来显示。我用 RoundingMode.HALF_EVEN
由于美元使用 2 位小数,半偶数四舍五入的数字应为 225.04 美元。但我得到了 225.05 美元。
这是我的代码(我更改它以创建一个 MWE):
@Override
public String toString() {
Currency cur = Currency.getInstance("USD");
BigDecimal result = new BigDecimal("225.0453");
result = result.setScale(cur.getDefaultFractionDigits(),RoundingMode.HALF_EVEN);
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setCurrency(cur);
nf.setMaximumFractionDigits(cur.getDefaultFractionDigits());
return nf.format(result.doubleValue());
}
此外,我也很高兴有更好的解决方案,因为这似乎不太正确。 (我试过 nf.setRoundingMode
但根本没用)
仅当值在可能的舍入目标之间等距时,RoundingMode
HALF_EVEN
才向偶数邻居舍入。
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
这意味着如果金额为等距值 225.045,它将向下舍入。但是因为你的225.0453的数量大于等距值,所以还是会向上取整。
有人请告诉我我犯的错误:
我有号码:225.0453,内部保存为 4 位数字。这是一个美元货币数字,我想要漂亮的印刷品来显示。我用 RoundingMode.HALF_EVEN
由于美元使用 2 位小数,半偶数四舍五入的数字应为 225.04 美元。但我得到了 225.05 美元。
这是我的代码(我更改它以创建一个 MWE):
@Override
public String toString() {
Currency cur = Currency.getInstance("USD");
BigDecimal result = new BigDecimal("225.0453");
result = result.setScale(cur.getDefaultFractionDigits(),RoundingMode.HALF_EVEN);
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setCurrency(cur);
nf.setMaximumFractionDigits(cur.getDefaultFractionDigits());
return nf.format(result.doubleValue());
}
此外,我也很高兴有更好的解决方案,因为这似乎不太正确。 (我试过 nf.setRoundingMode
但根本没用)
仅当值在可能的舍入目标之间等距时,RoundingMode
HALF_EVEN
才向偶数邻居舍入。
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
这意味着如果金额为等距值 225.045,它将向下舍入。但是因为你的225.0453的数量大于等距值,所以还是会向上取整。