Guillaume Massé
Guillaume Massé

Reputation: 8064

Distinguish zero and negative zero with java.math.BigDecimal

Is it possible to distinguish new BigDecimal(-0D) from new BigDecimal(0D)?

Upvotes: 3

Views: 3920

Answers (2)

Stephen C
Stephen C

Reputation: 719436

The javadoc states:

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale.

The value of the number represented by the BigDecimal is therefore (unscaledValue × 10scale).

Since there is only one integer value for zero, it is impossible to represent "minus zero" as a BigDecimal.


Internally, the standard implementation of BigDecimal uses a BigInteger to represent the "unscaled value". While the javadocs don't include this implementation detail as part the specification, the definition quoted above is sufficient to preclude any implementation where there were two distinct values for positive and negative zero.

There can of course be multiple values for zero; e.g. 0 and 0.00 are not equal. This follows from the definition of BigDecimal::equals(Object).

Upvotes: 1

Mark Rotteveel
Mark Rotteveel

Reputation: 109239

There is no way to distinguish this, because java.math.BigDecimal only knows a single zero(*). It doesn't have the concept of positive or negative zero.

This is because internally, BigDecimal uses BigInteger, and BigInteger also only has a single concept of zero. A BigInteger behaves as a two's-complement integer, and two's-complement only has a single zero.

See also this comment in the BigInteger sources:

public class BigInteger extends Number implements Comparable<BigInteger> {
    /**
     * The signum of this BigInteger: -1 for negative, 0 for zero, or
     * 1 for positive.  Note that the BigInteger zero <em>must</em> have
     * a signum of 0.  This is necessary to ensures that there is exactly one
     * representation for each BigInteger value.
     */
    final int signum

*: Not entirely accurate, you can have multiple zeroes with differing scale, just not with differing sign

Upvotes: 9

Related Questions