我正在减去两个bigDecimal数。进入减法,它们都具有非零精度,但是结果的精度为0。

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


  精度是非标度值中的位数。例如,对于数字123.45,返回的精度为5。


(另请参见BigDecimal, precision and scale)。

问题区域:

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


centerHP.getReal()返回从此行创建的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是一个值为-1.79的bigDecimal,int表示形式应为-179,精度为3,小数位数为2。值如下:



测试等于:



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

最佳答案

在此字段的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;
}

关于java - 减去bigDecimal数字会产生0的精度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55680691/

10-11 22:49
查看更多