我有以下函数迭代一个数组,在每个“Refund”对象上调用一个方法,返回一个包含一些值的 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”。我知道我传递的数组不为空,并且它们的“getAmountPayable()”函数返回的值也不为空或等于 0。我不知道我是否一直在盯着这太久了,我错过了显而易见的,一些帮助将不胜感激。
PS - 'getAmountPayble()' 返回一个 BigDecimal 类型的值
最佳答案
需要使用add
的返回值,因为BigDecimal
是不可变的。所以你想要:
total = total.add(refund.getAmountPayable());
(我个人认为如果该方法被称为 plus
而不是 add
会更明显,但没关系。)
关于java - 如何添加到 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773572/