gpt4 book ai didi

java - BigDecimal 舍入模式问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:13 25 4
gpt4 key购买 nike

我需要使用 BigDecimal roundingmode.xxx 和 setScale(2) 获得这些结果:

(5.789).setScale(2, RoundingMode.xxx) = 5.79

(2.894).setScale(2, RoundingMode.xxx) = 2.89

(2.895).setScale(2, RoundingMode.xxx) = 2.89

其中 RoundingMode.xxx 对于三个给定值必须相同

我尝试了所有组合但没有成功,Microsoft Excel 成功设置了三个结果。

最佳答案

你可以使用 ROUND_HALF_DOWN :

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for ROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as for ROUND_DOWN.

供您输入:

static void roundTo(BigDecimal input)
{
BigDecimal output = input.setScale(2, BigDecimal.ROUND_HALF_DOWN);
System.out.println(input + " => " + output);
}

roundTo(new BigDecimal("5.789"));
roundTo(new BigDecimal("2.894"));
roundTo(new BigDecimal("2.895"));

这会产生:

5.789 => 5.79
2.894 => 2.89
2.895 => 2.89

编辑:根据您的意见,以下内容可能对您有用:

BigDecimal output = input.setScale(3, BigDecimal.ROUND_HALF_DOWN).setScale(2, BigDecimal.ROUND_HALF_DOWN);

关于java - BigDecimal 舍入模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546053/

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