Why doesn't BigDecimal.stripTrailingZeros() remove always all trailing zeros?
bigdecimal, java, rounding
Solution
BigDecimal d = new BigDecimal("0.0000");
System.out.println(d.stripTrailingZeros());
prints `0.0000` with Java 7 but `0` with Java 8. This is apparently a bug that has been fixed in Java 8.
Problem
I do the following ``` 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(); ``` In case the input is now "-0.000987654321" (= value) I get back "-0.001" (= return Value) which is ok. In case the input is now "-0.0000987654321" I get back "-0.0001" which is also ok. But when the input is now "-0.00000987654321" I get back "0.0000" instead of "0" which is not ok. What is wrong here? Why aren't the trailing zeros removed in this case?