Addition for BigDecimal

Sergio del Amo picture Sergio del Amo · Dec 4, 2009 · Viewed 227.9k times · Source

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?

Answer

Vincent Ramdhanie picture Vincent Ramdhanie · Dec 4, 2009

The BigDecimal is immutable so you need to do this:

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