我在代码中遇到了奇怪的错误.
它涉及到
new BigDecimal("1.2300").stripTrailingZeros()
Run Code Online (Sandbox Code Playgroud)
返回1.23(正确)
但
new BigDecimal("0.0000").stripTrailingZeros()
Run Code Online (Sandbox Code Playgroud)
返回0.0000(奇怪),因此没有任何反应
为什么?
怎么解决?
为什么以下代码打印0.00而不是0?
BigDecimal big = new BigDecimal("0.00");
big = big.stripTrailingZeros();
System.out.println(big.toPlainString());
Run Code Online (Sandbox Code Playgroud)
以下是stripTrailingZeroes的文档:
返回BigDecimal,它在数值上等于此值,但从表示中删除了任何尾随零.例如,从BigDecimal值600.0剥离尾随零,其中[BigInteger,scale]组件等于[6000,1],产生6E2,[BigInteger,scale]组件等于[6,-2]
返回:
数字等于BigDecimal,删除任何尾随零.
我做了以下事情
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();
Run Code Online (Sandbox Code Playgroud)
如果输入现在为"-0.000987654321"(=值),我返回"-0.001"(=返回值)即可.
如果输入现在为"-0.0000987654321",我会返回"-0.0001",这也没关系.
但是当输入现在是"-0.00000987654321"时,我得到"0.0000"而不是"0",这是不行的.这有什么不对?为什么在这种情况下不删除尾随零?