gpt4 book ai didi

Java BigDecimal : Round to the nearest whole value

转载 作者:IT老高 更新时间:2023-10-28 11:41:31 26 4
gpt4 key购买 nike

我需要以下结果

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

.round() 还是 .setScale() ?我该怎么办?

最佳答案

您可以使用 setScale() 将小数位数减少为零。假设 value 持有要四舍五入的值:

BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);

使用 round() 有点复杂,因为它需要您指定要保留的位数。在您的示例中,这将是 3,但这并非对所有值都有效:

BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);

(请注意,BigDecimal 对象是不可变的;setScaleround 都会返回一个新对象。)

关于Java BigDecimal : Round to the nearest whole value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4134047/

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