I have met strange bug in my code.
It relates with
new BigDecimal("1.2300").stripTrailingZeros()
returns 1.23(correct)
but
new BigDecimal("0.0000").stripTrailingZeros()
returns 0.0000(strange), thus nothing happens
Why?
How to fix it?
I have met strange bug in my code.
It relates with
new BigDecimal("1.2300").stripTrailingZeros()
returns 1.23(correct)
but
new BigDecimal("0.0000").stripTrailingZeros()
returns 0.0000(strange), thus nothing happens
Why?
How to fix it?
Seems that this is a bug (JDK-6480539) which was fixed in Java 8 (per OpenJDK commit 2ee772cda1d6).
Workaround for earlier versions of Java:
BigDecimal zero = BigDecimal.ZERO;
if (someBigDecimal.compareTo(zero) == 0) {
someBigDecimal = zero;
} else {
someBigDecimal = someBigDecimal.stripTrailingZeros();
}
Here's the Javadoc for that method, which certainly suggests that isn't the intended behaviour, but isn't conclusive: http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#stripTrailingZeros()
Exactly why it isn't doing this is down to the implementation then. Which JDK are you using? For OpenJDK, we can see the source to figure out how it's reaching this conclusion, but other JDKs may differ.