gpt4 book ai didi

java - 为什么 BigDecimal.stripTrailingZeros() 不总是删除所有尾随零?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:28 25 4
gpt4 key购买 nike

我做了以下事情

    MathContext context = new MathContext(7, RoundingMode.HALF_UP);
BigDecimal roundedValue = new BigDecimal(value, context);

// Limit decimal places
try {
roundedValue = roundedValue.setScale(decimalPlaces, RoundingMode.HALF_UP);
} catch (NegativeArraySizeException e) {
throw new IllegalArgumentException("Invalid count of decimal places.");
}
roundedValue = roundedValue.stripTrailingZeros();

String returnValue = roundedValue.toPlainString();

如果输入现在是“-0.000987654321”(= 值),我会返回“-0.001”(= 返回值),这没问题。

如果输入现在是“-0.0000987654321”,我会返回“-0.0001”,这也可以。

但是当输入现在是“-0.00000987654321”时,我得到的是“0.0000”而不是“0”,这是不对的。这里有什么问题?为什么在这种情况下不删除尾随零?

最佳答案

BigDecimal d = new BigDecimal("0.0000");
System.out.println(d.stripTrailingZeros());

使用 Java 7 打印 0.0000 但使用 Java 8 打印 0。这显然是一个 bug那是fixed在 Java 8 中。

关于java - 为什么 BigDecimal.stripTrailingZeros() 不总是删除所有尾随零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21384817/

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