Addition for BigDecimal

Viewed 263696

I want to do some simple sums with some currency values expressed in BigDecimal type.

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test.add(new BigDecimal(30));
System.out.println(test);
test.add(new BigDecimal(45));
System.out.println(test);

Obviously I do not understand well the BigDecimal arithmetics, see output behind.

Test
0
0
0

Can anyone help me out?

12 Answers

BigInteger is immutable, just like Strings. That means we cannot change it's content once the object is created, but we can re-assign it.

 BigInteger sum = test.add(new BigInteger(30));  
 System.out.println(sum);

.add() will return a new Object

Using Java8 lambdas

List<BigDecimal> items = Arrays.asList(a, b, c, .....);

items.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

This covers cases where the some or all of the objects in the list is null.

Related