Java – how to add to BigDecimal
•
Java
I have the following function, which iterates an array and calls a method on each 'return' object, which returns a BigDecimal containing some values, such as 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(); }
The problem is that it always returns' 0.00 ' I know that the array I passed is not null, and the value returned by the 'getamountpayable()' function is not null or equal to 0 I don't know if I've been staring at this too long. I missed the obvious. Some help will be very grateful
PS – 'getamountpay()' returns a value of type BigDecimal
Solution
You need to use the return value of add because BigDecimal is immutable So you should:
total = total.add(refund.getAmountPayable());
(personally, if this method is called a plus sign instead of adding, it will be more obvious. But it doesn't matter.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码