BigDecimal stripTrailingZeros doesn't work for zero

大憨熊 提交于 2019-12-09 15:42:02

问题


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?


回答1:


Seems that it is a bug. But it is fixed in Java 8. Direct URL for fix.

There is workaround for this:

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

Please refer to this link.

Also good point from Holger in comments

Don’t waste resources creating your own zero instance. Use BigDecimal.ZERO.




回答2:


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.



来源:https://stackoverflow.com/questions/34414785/bigdecimal-striptrailingzeros-doesnt-work-for-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!