【发布时间】:2016-06-05 18:03:10
【问题描述】:
我有这样的代码
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()));
为什么我收到 totalPrice.add 被忽略而 withoutTax.add 工作正常?
【问题讨论】:
-
您分配了
withoutTax.add的结果,而忽略了totalPrice.add的结果。如果您不想忽略结果,请将其分配给变量,就像您为withoutTax.add所做的那样 -
仅供参考: 不鼓励使用
BigDecimal(double val)。请参阅javadoc 了解原因。 --- 在add()调用上指定new MathContext(5)是不必要的。
标签: java bigdecimal currency