RFR - 6480539: BigDecimal.stripTrailingZeros() should specify no-op on zero BigDecimals

Joe Darcy joe.darcy at oracle.com
Mon Feb 4 19:31:35 UTC 2013

On 2/4/2013 10:13 AM, Stephen Colebourne wrote:
> On 4 February 2013 18:09, Brian Burkhalter <brian.burkhalter at oracle.com> wrote:
>> While stripTrailingZeros() should perhaps for purity of specification always return BigDecimal.ZERO for anything which is numerically equal to zero, the present behavior of this method has been extant for some years, so following the prevailing convention it would be preferable to modify the specification to match the behavior.
>> Proposed change:
>> diff -r 20eeb727d171 -r 8789e8736763 src/share/classes/java/math/BigDecimal.java
>> --- a/src/share/classes/java/math/BigDecimal.java       Fri Feb 01 16:32:53 2013 -0800
>> +++ b/src/share/classes/java/math/BigDecimal.java       Fri Feb 01 16:32:53 2013 -0800
>> @@ -2589,7 +2589,9 @@
>>        * the {@code BigDecimal} value {@code 600.0}, which has
>>        * [{@code BigInteger}, {@code scale}] components equals to
>>        * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
>> -     * {@code scale}] components equals to [6, -2]
>> +     * {@code scale}] components equals to [6, -2]. This method has no
>> +     * effect on a {@code BigDecimal} <i>x</i> which is numerically
>> +     * equal to zero, i.e., {@code x.compareTo(BigDecimal.ZERO) == 0}.
>>        *
>>        * @return a numerically equal {@code BigDecimal} with any
>>        * trailing zeros removed.
> This is a bug that has bitten me on more than one occasion. Changing
> the spec is not the solution here. Fixing the bug is.
> Stephen

The stripTrailingZeros method has acted in this surprising way since the 
IBM-led JSR 13 was integrated into the platform back in JDK 5, which 
shipped in 2004.

This situation is analogous to when the specification and behavior 
disagree.  Our general policy to resolve such cases when evolving the 
JDK is:

"..., there are times in evolving the JDK when differences are found 
between the specified behavior and the actual behavior (for example 
4707389, 6365176). The two basic approaches to fixing these bugs are to 
change the implementation to match the specified behavior or to change 
the specification (in a platform release) to match the implementation's 
(perhaps long-standing) behavior; often the latter option is chosen 
since it has a lower de facto impact on behavioral compatibility."

If this issue were being addressed before JDK 5 shipped or even during 
JDK 6, I would support changing the behavior of stripTrailingZeros.  
However, for addressing this in JDK 8, I think it is more appropriate to 
keep the behavior as-is and document this special case.


More information about the core-libs-dev mailing list