Search code examples
javabigdecimal

BigDecimal stripTrailingZeros and equality


Given

BigDecimal a = ...;
BigDecimal b = ...;

Do the following hold for all possible values of a and b?

if (a.compareTo(b) == 0)
    assert a.stripTrailingZeros().equals(b.stripTrailingZeros())
if (a.compareTo(b) != 0)
    assert !(a.stripTrailingZeros().equals(b.stripTrailingZeros()))

if (a.stripTrailingZeros().equals(b.stripTrailingZeros()))
    assert(a.compareTo(b) == 0)
if (!(a.stripTrailingZeros().equals(b.stripTrailingZeros())))
    assert(a.compareTo(b) != 0)

Or is there some edge case where the above assertions are not all true?


Solution

  • Note that stripTrailingZeros can throw an ArithmeticException if the resulting scale overflows. For example;

    new BigDecimal(
            new BigInteger("70"),
            Integer.MIN_VALUE
    ).stripTrailingZeros(); // tries to set the scale to Integer.MIN_VALUE - 1 but can't
    

    Other than such cases, the assertion should be true, because there is only one unique BigDecimal representation of each number, that has no trailing zeroes.