2014-11-06 31 views
6

我有以下函數在數組上傳輸,在每個返回包含某個值的BigDecimal的'Refund'對象上調用一個方法,例如20.45:如何添加到BigDecimal

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,並且它們的'getAmountPayable()'函數返回的值也不爲零或等於0.我不知道我是否一直盯着這太久了,我錯過了明顯的,一些幫助將不勝感激。

PS - 'getAmountPayble()返回類型爲BigDecimal

+0

你可能想使用常量['BigDecimal.ZERO'(http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#ZERO) – 2014-11-06 07:08:56

回答

12

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

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

(我個人認爲,這將是比較明顯的,如果該方法被稱爲plus而非add,不過沒關係。)

+0

完美,非常感謝。這確實是問題。 :) – Tiwaz89 2014-11-06 07:07:33

+0

@Relborg接受在這種情況下的答案:) – 2014-11-06 07:11:57

+0

@DanTemple會做,不得不等待幾分鐘 – Tiwaz89 2014-11-06 07:39:13

0

喬恩斯基特的答案是正確的。下面是BigDecimal#add的API的Javadoc:

返回BigDecimal,其值爲(this +被加數),其標是爲max(this.scale(),augend.scale())。