gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:09:57 35 4
gpt4 key购买 nike

我正在处理两个 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, precision and scale)。

相关区域:

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

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

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

对于上下文 center.real = -0.79 这是一个 double 值。

所以它是有效的

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。但是紧接在BigDecimal中的subtract方法中的加法运算类,我的值(value)观如下:

right after addition

和测试等于:

test value

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

最佳答案

根据该字段的 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com