为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地8271018 2022-10-07 16:32:16
我正在减去两个 bigDecimal 数字。进入减法方法,它们都具有非零精度,但结果精度= 0。据我所知,精度为 0 的 bigDecimal 数是不可能的。即使 0 的精度为 1。精度是未缩放值中的位数。例如,对于数字 123.45,返回的精度为 5。(另见BigDecimal、precision 和 scale)。有问题的区域:BigDecimal test = (centerHP.getReal().subtract(inverseScale));centerHP.getReal()返回从该行创建的bigDecimalnew BigDecimal(Double.toString(center.getReal()))对于上下文center.real = -0.79,它是双精度的。所以它是有效的new BigDecimal("-0.79")inverseScale 只是 1double scale = 1;BigDecimal inverseScale = (BigDecimal.ONE.divide(new BigDecimal(Double.toString(scale))));我希望 test 是一个值为 -1.79 的 bigDecimal,int 表示应该是 -179,精度为 3,小数位数为 2。但是,紧随 BigDecimal 类中减法方法中的加法运算之后,我的值如下:和测试等于:请注意,所有其他值都是正确的,只是精度似乎是错误的。
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

从该字段的 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;

}


查看完整回答
反对 回复 2022-10-07
  • 1 回答
  • 0 关注
  • 244 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号