减去 bigDecimal 数字产生的精度为 0?

Subtracting bigDecimal numbers produces a precision of 0?

我正在处理两个 bigDecimal 数的减法。进入减法方法,它们都具有非零精度但结果具有精度= 0。

据我所知,精度为 0 的 bigDecimal 数是不可能的。甚至 0 的精度为 1.

The precision is the number of digits in the unscaled value. For instance, for the number 123.45, the precision returned is 5.

(另见 )。

相关区域:

BigDecimal test = (centerHP.getReal().subtract(inverseScale));

centerHP.getReal() returns 从这一行创建的 bigDecimal

new BigDecimal(Double.toString(center.getReal()))

上下文 center.real = -0.79 是双精度的。

所以它是有效的

new BigDecimal("-0.79")

inverseScale 就是 1

double scale = 1;

BigDecimal inverseScale = (BigDecimal.ONE.divide(new BigDecimal(Double.toString(scale))));

我希望test是一个bigDecimal,值为-1.79,int表示应该是-179,精度为3,小数位数为2。但是,紧接在subtract方法中的加法运算之后BigDecimalclass,我的取值如下:

并且测试等于:

请注意,所有其他值都是正确的,只是精度似乎有误。

根据该字段的 javadoc,0 表示精度未知。

/**
 * The number of decimal digits in this BigDecimal, or 0 if the
 * number of digits are not known (lookaside information).  If
 * nonzero, the value is guaranteed correct.  Use the precision()
 * method to obtain and set the value if it might be 0.  This
 * field is mutable until set nonzero.
 *
 * @since  1.5
 */
private transient int precision;

方法 precision() 延迟确定精度。

public int precision() {
    int result = precision;
    if (result == 0) {
        long s = intCompact;
        if (s != INFLATED)
            result = longDigitLength(s);
        else
            result = bigDigitLength(inflate());
        precision = result;
    }
    return result;
}