Addition for Bigdecimal

Addition for BigDecimal

The BigDecimal is immutable so you need to do this:

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

BigDecimal += (add and assign) ...How to do this?

There is an add method in the BigDecimal class.

You would have to do - a = a.add(b);

Have a look at the java docs.

BigDecimal.add() being ignored

That's answered by looking at the docs for BigDecimal

Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).

Emphasis mine. So add doesn't modify the existing BigDecimal - it can't, since BigDecimals are immutable. According to the docs, BigDecimals are

Immutable, arbitrary-precision signed decimal numbers.

Instead of modifying its value, it returns a new value which is equal to the result of the addition.

Change this:

totalPrice.add(withTax, new MathContext(5));

to this:

totalPrice = totalPrice.add(withTax, new MathContext(5));

to assign that new value back to the same variable, and it will correctly update like you expect.

Compare that to this line:

withTax = withoutTax.add(tax, new MathContext(5));

You wouldn't expect the value of withoutTax to change simply because you used it in a calculation. In order for that line to work as expected, the add method cannot be allowed to modify the object it is called on.

adding 2 BigDecimal values

BigDecimal is immutable. Every operation returns a new instance containing the result of the operation:

 BigDecimal sum = x.add(y);

If you want x to change, you thus have to do

x = x.add(y);

Reading the javadoc really helps understanding how a class and its methods work.

How Can I perform Addition on Big Decimal?

Looks like you are trying to avoid 1E-10 expression
you can do that as

BigDecimal bigD = new BigDecimal("0.0000000000").add(new BigDecimal("0.0000000001"));
System.out.println(bigD.toPlainString());

adding values from a BigDecimal [ ]

Assuming that you are adding an array of Strings containing valid numbers you could do this:

BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < select.length; i++)
{
sum = sum.add(new BigDecimal(select[i]));
}
out.println(sum);

The array total[] is pretty much redundant. You can move your sum declaration and out.println(sum); out of your loop.



Related Topics



Leave a reply



Submit