BigDecimal.add()方法

BigDecimal.add()方法误区:

BigDecimal totalAmount = new BigDecimal("666");
totalAmount.add(new BigDecimal("888"));
System.out.println(totalAmount);

此时输出并不是加之后的值,而是加之前的值,是因为源码中有介绍@return {@code this + augend}
返回值才是需要的结果,而不是在原数据上进行操作。

// Arithmetic Operations
    /**
     * Returns a {@code BigDecimal} whose value is {@code (this +
     * augend)}, and whose scale is {@code max(this.scale(),
     * augend.scale())}.
     *
     * @param  augend value to be added to this {@code BigDecimal}.
     * @return {@code this + augend}
     */
    public BigDecimal add(BigDecimal augend) {
        if (this.intCompact != INFLATED) {
            if ((augend.intCompact != INFLATED)) {
                return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
            } else {
                return add(this.intCompact, this.scale, augend.intVal, augend.scale);
            }
        } else {
            if ((augend.intCompact != INFLATED)) {
                return add(augend.intCompact, augend.scale, this.intVal, this.scale);
            } else {
                return add(this.intVal, this.scale, augend.intVal, augend.scale);
            }
        }
    }

正确结果应是其返回值:

BigDecimal totalAmount = new BigDecimal("666");
totalAmount.add(new BigDecimal("888"));
System.out.println(totalAmount);
BigDecimal result = totalAmount.add(new BigDecimal("888"));
System.out.println(result);

输出:
BigDecimal.add()方法_第1张图片

你可能感兴趣的:(Java,java)