gpt4 book ai didi

java - BigDecimal 不正确的舍入

转载 作者:行者123 更新时间:2023-12-02 05:03:51 25 4
gpt4 key购买 nike

我有这个除法结果:

4893.305785123966785163027491292661448576748

我想四舍五入到 4893.30,但它总是返回 4893.31。但当第二位小数为 6 或更多时,我想四舍五入。

new BigDecimal("4893.305785123966785163027491292661448576748").setScale(2,BigDecimal.ROUND_HALF_DOWN)); to 4893.31 //BAD

new BigDecimal("4893.305").setScale(2,BigDecimal.ROUND_HALF_DOWN)); to 4893.30 //OK

new BigDecimal("4893.3055").setScale(2,BigDecimal.ROUND_HALF_DOWN)); to 4893.31 //BAD

回合如何进行?我只想考虑第二位小数的值。有什么想法吗?

最佳答案

"How does the round work? I want to take in consideration only the value of the second decimal."

听起来您想截断而不是舍入。

而不是使用 ROUND_HALF_DOWN :

Rounding mode to round towards "nearest neighbor"...

...相反,尝试使用 ROUND_DOWN :

Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates)...

例如

    BigDecimal bd = new BigDecimal("4893.305785123966785163027491292661448576748");
bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
System.out.println(bd); // 4893.30

更新回答问题编辑

如果您只想考虑某些小数位,那就是截断后跟四舍五入:

    BigDecimal bd = new BigDecimal("4893.305785123966785163027491292661448576748");
bd = bd.setScale(3, BigDecimal.ROUND_DOWN); // truncate to 4893.305
bd = bd.setScale(2, BigDecimal.ROUND_HALF_DOWN); // round to 2 decimal places
System.out.println(bd); // 4893.30

bd = new BigDecimal("4893.306785123966785163027491292661448576748");
bd = bd.setScale(3, BigDecimal.ROUND_DOWN); // truncate to 4893.306
bd = bd.setScale(2, BigDecimal.ROUND_HALF_DOWN); // round to 2 decimal places
System.out.println(bd); // 4893.31

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

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