Bigdecima判断是否为零(compareTo比较大小)

作者: java 发布时间: 2023-01-16 浏览: 2075 次 编辑

注意:b.equals(BigDecimal.ZERO)方法存在问题,用b.compareTo(BigDecimal.ZERO)方法判断


一、bigdecimal判断是否为零

1.判断Bigdecimal类型是否等于0的方法b.equals(BigDecimal.ZERO);

用equals方法和BigDecimal.ZERO进行比较。

注意:上面判断是否等于零存在的问题:

我们来查看源代码:

    /**
     * Compares this {@code BigDecimal} with the specified
     * {@code Object} for equality.  Unlike {@link
     * #compareTo(BigDecimal) compareTo}, this method considers two
     * {@code BigDecimal} objects equal only if they are equal in
     * value and scale (thus 2.0 is not equal to 2.00 when compared by
     * this method).
     *
     * @param  x {@code Object} to which this {@code BigDecimal} is
     *         to be compared.
     * @return {@code true} if and only if the specified {@code Object} is a
     *         {@code BigDecimal} whose value and scale are equal to this
     *         {@code BigDecimal}'s.
     * @see    #compareTo(java.math.BigDecimal)
     * @see    #hashCode
     */
    @Override
    public boolean equals(Object x) {
        if (!(x instanceof BigDecimal))
            return false;
        BigDecimal xDec = (BigDecimal) x;
        if (x == this)
            return true;
        if (scale != xDec.scale)
            return false;
        long s = this.intCompact;
        long xs = xDec.intCompact;
        if (s != INFLATED) {
            if (xs == INFLATED)
                xs = compactValFor(xDec.intVal);
            return xs == s;
        } else if (xs != INFLATED)
            return xs == compactValFor(this.intVal);

        return this.inflated().equals(xDec.inflated());
    }

Bigdecimal的equals方法不仅仅比较值的大小是否相等,首先比较的是scale(scale是bigdecimal的保留小数点位数,比如 new Bigdecimal(“1.001”),scale为3),

也就是说,不但值得大小要相等,保留位数也要相等,equals才能返回true。

Bigdecimal b = new Bigdecimal(“0”) 和 Bigdecimal c = new Bigdecimal(“0.0”),用equals比较,返回就是false。

Bigdecimal.ZERO的scale为0。

所以,用equals方法要注意这一点。


二、我们还可以用compareTo判断Bigdecimal类型的值是否为0:

b.compareTo(BigDecimal.ZERO)==0,可以比较是否等于0,返回true则等于0,返回false,则不等于0