问题
Why the following code prints 0.00
and not 0
?
BigDecimal big = new BigDecimal("0.00");
big = big.stripTrailingZeros();
System.out.println(big.toPlainString());
The following is the documentation for stripTrailingZeroes:
Returns BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. For example, stripping the trailing zeros from the BigDecimal value 600.0, which has [BigInteger, scale] components equals to [6000, 1], yields 6E2 with [BigInteger, scale] components equals to [6, -2]
Returns:
a numerically equal BigDecimal with any trailing zeros removed.
回答1:
It strips the trailing zeroes of the internal representation [6000,1]
and adapts the scale accordingly 1 -> -2
. The internal representation is also somewhat independent of the final print-out which is also affected by format, rounding and locale.
回答2:
I think it's a bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6480539
来源:https://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes