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?
BigDecimal is zero means that it can store 0, 0.0 or 0.00 etc values. So you want to check Integer is zero and the precision is also zero. BigDecimal object has enum constant BigDecimal. ZERO to represent 0 value with zero scales.
stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.
BigDecimal represents an immutable arbitrary-precision signed decimal number. It consists of two parts: Unscaled value – an arbitrary precision integer. Scale – a 32-bit integer representing the number of digits to the right of the decimal point.
public enum RoundingMode extends Enum<RoundingMode> Specifies a rounding behavior for numerical operations capable of discarding precision. Each rounding mode indicates how the least significant returned digit of a rounded result is to be calculated.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With