Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal stripTrailingZeros doesn't work for zero

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?

like image 789
gstackoverflow Avatar asked Dec 22 '15 11:12

gstackoverflow


People also ask

What is the value of BigDecimal zero?

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.

How do I get rid of trailing zeros in BigDecimal?

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.

Does BigDecimal support decimal places?

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.

What is RoundingMode in BigDecimal Java?

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.


1 Answers

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();
}
like image 122
Yuri Avatar answered Nov 07 '22 00:11

Yuri