BigDecimal stripTrailingZeros not working for zero

I met a strange error in my code.

It refers to

new BigDecimal("1.2300").stripTrailingZeros() 

returns 1.23 (correct)

but

 new BigDecimal("0.0000").stripTrailingZeros() 

returns 0.0000 (strange), so nothing happens

Why?

How to fix it?

+6
source share
2 answers

This seems like a mistake . But it is fixed in Java 8 . Direct URL to fix .

There is a workaround for this:

 BigDecimal zero = BigDecimal.ZERO; if (someBigDecimal.compareTo(zero) == 0) { someBigDecimal = zero; } else { someBigDecimal = someBigDecimal.stripTrailingZeros(); } 

Refer to this link .

Also a good point from Holger in the comments

Do not waste resources on creating your own zero instance. Use BigDecimal.ZERO .

+8
source

Here's the Javadoc for this method, which certainly assumes that this is not the intended behavior, but is not final: http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#stripTrailingZeros ()

That is why this does not mean that this happens before implementation. Which JDK are you using? For OpenJDK, we can see the source to figure out how it reaches this output, but other JDKs may be different.

0
source

All Articles