javabigdecimal

Addition for BigDecimal


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?


Solution

  • The BigDecimal is immutable so you need to do this:

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