我正在处理两个 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 是一个值为 -1.79 的 bigDecimal,int 表示应该是 -179,精度为 3,小数位数为 2。但是,紧接着 BigDecimal 中的 minus 方法中的加法运算类,我的值(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/