gpt4 book ai didi

java - BigDecimal setScale 使用舍入模式一半甚至不起作用

转载 作者:行者123 更新时间:2023-12-01 19:50:06 27 4
gpt4 key购买 nike

有人请告诉我我犯的错误:

我的号码:225.0453,内部保存有 4 位数字。这是一个美元货币数字,我想要 pretty-print 来显示。我用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 大于等距值,因此仍会向上舍入。

关于java - BigDecimal setScale 使用舍入模式一半甚至不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51603129/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com