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

标签 java bigdecimal

我正在处理两个 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)观如下:

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/

相关文章:

java - 使用tomcat作为服务器在eclipse ide的服务器上运行网站

java - 使用 Java 中的 Windows API 调用使用 "native"

Java DecimalFormat 在格式化 double 时失去精度

java - 如何在使用 Stream 的同时将 Long 转换为 BigDecimal

java - BigDecimal 中 Divide 方法的 Scale()

java - Jhipster - MySQL java.sql.SQLException : Access denied for user 'root' @'localhost' (using password: NO) 错误

返回接口(interface)类型的 Java 方法

java - Postgresql 与 Java 中的数据库连接失败

Groovy BigDecimal 精度问题

java - 一个功能更丰富的数字(比 Bigdecimal)持有 java 库