How to sum Bigdecimal values in java?

Handling bigdecimal values can be tricky. Here we will look at 2 approaches for getting sum of BigDecimal numbers

1. Using for loops

We can use traditional approach of using for loop for getting sum of the BigDecimal numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.harishgowda84.java8;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class BigDecimalDemo {

    public static void main(String[] args) {

        List<BigDecimal> numbers = Arrays.asList(
                new BigDecimal(8.9),
                new BigDecimal(14.5),
                new BigDecimal(123.67),
                new BigDecimal(25.6),
                new BigDecimal(4.3)
        );

        BigDecimal sum= BigDecimal.ZERO;

        for(BigDecimal element: numbers){
            sum= sum.add(element);
        }

        System.out.println("Sum of all values is: "+sum);

    }
}
1
Sum of all values is: 176.97000000000000330402372128446586430072784423828125

2. Using Streams

Follow below steps to get sum of all decimal values

  1. Create a List of BigDecimal numbers that you want to sum.
  2. Convert the list to a stream using the stream() method.
  3. Use the reduce() method on the stream to sum the BigDecimal numbers.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.harishgowda84.java8;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class BigDecimalDemo {

    public static void main(String[] args) {

        List<BigDecimal> numbers = Arrays.asList(
                new BigDecimal(8.9),
                new BigDecimal(14.5),
                new BigDecimal(123.67),
                new BigDecimal(25.6),
                new BigDecimal(4.3)
        );

        BigDecimal sum = numbers.stream().reduce(BigDecimal.ZERO,BigDecimal::add);

        System.out.println("Sum of all values is: "+sum);


    }
}
1
Sum of all values is: 176.97000000000000330402372128446586430072784423828125

We have used reduce() method with an initial value of BigDecimal.ZERO and a binary operator of BigDecimal::add to sum the BigDecimal numbers in the stream. Finally, we printed the sum to the console.