java - 如何添加到 BigDecimal

标签 java

我有以下函数迭代一个数组,在每个“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/

相关文章:

java - synset 中的 wordnet 词组

java - 在没有应用程序策略的情况下对 JBoss 中的数据源密码进行加密

java - 在 spring 集成中将多个有效负载嵌入到 "Message"对象中的最佳方法是什么?

java - 在字符串中找不到模式

java - 在 Tomcat 服务器上自动启动 Spring Boot 应用程序

java - 从 config.properties 文件读取路径

java - 如何在使用流读取文件时保留换行符 - java 8

当 content-type 为 application/x-www-form-urlencoded 时,Java 读取 POST 数据

java - "Comparison method violates its general contract!"

java - 嵌套映射结构