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 1:
The BigDecimal
is immutable so you need to do this:
BigDecimal result = test.add(new BigDecimal(30));
System.out.println(result);
Solution 2:
It looks like from the Java docs here that add returns a new BigDecimal:
BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);
Solution 3:
BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);