Java 如何添加到BigDecimal

Java 如何添加到BigDecimal,java,Java,我使用以下函数对数组进行排序,对每个“退款”对象调用一个方法,该对象返回一个包含某些值的BigDecimal,例如20.45: private String getTransactionTotals(Refund[] refunds) { BigDecimal total = new BigDecimal(0.00); /* * Itterates over all the refund objects and adds * their amount

我使用以下函数对数组进行排序,对每个“退款”对象调用一个方法,该对象返回一个包含某些值的BigDecimal,例如20.45:

private String getTransactionTotals(Refund[] refunds) {

    BigDecimal total = new BigDecimal(0.00);

    /*
     *  Itterates over all the refund objects and adds
     *  their amount payables together to get a total 
     */
    for ( Refund refund : refunds ) {

        total.add(refund.getAmountPayable());           

    }

    total = total.setScale(2, RoundingMode.CEILING);
    return total.toString();
}   
问题是它总是返回“0.00”。我知道我传递的数组不是null,它们的“getAmountPayment()”函数retuns的值也不是null或等于0。我不知道我是否已经盯着这个太久了,我错过了显而易见的,一些帮助将不胜感激


PS-'GetAmountPayTable()'返回BigDecimal类型的值

您需要使用
add
的返回值,因为
BigDecimal
是不可变的。所以你想要:

total = total.add(refund.getAmountPayable());

(我个人认为,如果该方法被称为
plus
,而不是
add
,这一点会更加明显,但没关系。)

乔恩·斯凯特的答案是正确的。以下是API javadoc,用于:

返回一个BigDecimal,其值为(this+augend),其比例为max(this.scale(),augend.scale())


太好了,非常感谢。这确实是问题所在@在这种情况下,雷博格接受答案:)@DanTemple就可以了,需要等几分钟,尽管你可能想使用常量