Pau*_*aul 5 java rounding 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",这是不行的.这有什么不对?为什么在这种情况下不删除尾随零?
BigDecimal d = new BigDecimal("0.0000");
System.out.println(d.stripTrailingZeros());
Run Code Online (Sandbox Code Playgroud)
0.0000使用Java 7但0使用Java 8进行打印.这显然是Java 8中已修复的错误.