bigDecimal的比较

两个bigDecimal对象,如果要进行比较,用compareTo进行,而不要用 Objects.equals或者equal方法。

理解:
compareTo是比较大小, 与精度无关 。 大于是1 ,小于-1 等于返回0

 public int compareTo(BigDecimal val) {
        // Quick path for equal scale and non-inflated case.
        if (scale == val.scale) {
            long xs = intCompact;
            long ys = val.intCompact;
            if (xs != INFLATED && ys != INFLATED)
                return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
        }
        int xsign = this.signum();
        int ysign = val.signum();
        if (xsign != ysign)
            return (xsign > ysign) ? 1 : -1;
        if (xsign == 0)
            return 0;
        int cmp = compareMagnitude(val);
        return (xsign > 0) ? cmp : -cmp;
    }

equal和Objects.equals是比较两个对象是否相等。 如果要两个bigDecimal对象相等
前提是这两个对象的数值一样,精度一样。

 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());
    }

测试例子:

 public static void main(String[] args) {


        BigDecimal a = new BigDecimal("20000.0");

        BigDecimal b = new BigDecimal("20000.0000");

        System.out.println(Objects.equals(a, b));

        System.out.println(Objects.equals(a.setScale(8), b.setScale(8)));

        System.out.println(a.compareTo(b));

    }


bigDecimal的比较_第1张图片

因此 如果是数值型的比较,比如说我只想想判断两个金额是否想等 ,那么用compareTo

你可能感兴趣的:(遇到的bug)