gpt4 book ai didi

Java - 将 BigDecimal 值舍入到 2 个级别,保留 2 位小数

转载 作者:行者123 更新时间:2023-12-02 01:10:07 25 4
gpt4 key购买 nike

decimalValue=10.2345给出10.23使用以下代码进行四舍五入后

decimalValue.setScale(2, RoundingMode.HALF_UP)

我需要将值显示为 10.24 。找到了一种按 2 级舍入的解决方案,例如首先舍入到 3 位数字,然后舍入到 2 位数字,如下所示

decimalValue.setScale(3, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP)

如果有人有更好的解决方案,请提出建议。

最佳答案

RoundingMode.HALF_UP 将对 .5 及以上进行四舍五入。

HALF_UP

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode.UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for RoundingMode.DOWN.

改用RoundingMode.UP

decimalValue.setScale(2, RoundingMode.UP)

关于Java - 将 BigDecimal 值舍入到 2 个级别,保留 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530032/

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