Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum BigDecimal properties in java

Tags:

java

Let's get a simple example:

 Class Foo{
     private BigDecimal item1;
     private BigDecimal item2;
     private BigDecimal item3;
     private BigDecimal item4;
     private BigDecimal item5;
//setters and getters
   public BigDecimal getTotal(){
       BigDecimal total = BigDecimal.ZERO;
        if(null != item1){
            total =total .add(item1);
           }
        if(null != item2){
            total =total .add(item2);
           }
          ...
          ...
}
    }

I am summing in entity level. this is correct way or not?

can any one give me better code for getting total Value

like image 243
phani Avatar asked Dec 15 '25 15:12

phani


2 Answers

Use a List<BigDecimal>

public BigDecimal getTotal(){
    List<BigDecimal> values =  Arrays.asList(item1, item2, item3, item4, item5)

    BigDecimal total = BigDecimal.ZERO;
    for (BigDecimal value : values) {
        if(value != null) {
            total = total.add(value);
        }
    }
    return total;
}
like image 183
René Link Avatar answered Dec 17 '25 04:12

René Link


You can use a loop to make your code simple :

import java.util.Arrays;

...

public BigDecimal getTotal(){
   BigDecimal total = BigDecimal.ZERO; 
   for(BigDecimal bd: Arrays.asList(item1,item2,item3,item4,item5)){
        if(null != bd){
            total =total .add(bd);
           }
    }
}
like image 42
Mifmif Avatar answered Dec 17 '25 04:12

Mifmif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!