BigDecimal.add () is ignored

I have code like this

BigDecimal withoutTax, tax, withTax, totalPrice;
totalPrice = new BigDecimal(0.0);
BigDecimal amount = new BigDecimal(String.valueOf(table.getValueAt(table.getSelectedRow(), 3)).replace(",", "."));
BigDecimal price = new BigDecimal(String.valueOf(table.getValueAt(table.getSelectedRow(), 4)).replace(",", "."));
withoutTax = amount.multiply(price, new MathContext(5));
table.setValueAt(withoutTax.toPlainString(), table.getSelectedRow(), 5);
tax = withoutTax.multiply(new BigDecimal(0.23), new MathContext(2));
table.setValueAt(tax.toPlainString(), table.getSelectedRow(), 7);
withTax = withoutTax.add(tax, new MathContext(5));
table.setValueAt(withTax.toPlainString(), table.getSelectedRow(), 8);
totalPrice.add(withTax, new MathContext(5));
paymentNum.setText(String.valueOf(totalPrice.toPlainString()));

why do i get that totalPrice.addignored when it withoutTax.addworks correctly?

+4
source share
2 answers

Reply answered documents forBigDecimal

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

The emphasis is mine. Therefore, it adddoes not change the existing one BigDecimal- it cannot, because it is BigDecimalimmutable. According to the docs BigDecimal

Unmatched , decimal numbers with arbitrary precision.

, .

:

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

:

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

, , .

:

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

, withoutTax , . , , add , .

+20

, BigDecimal , BigDecimal, .

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

All Articles