为什么我的 BigDecimal 计算不起作用?

Why is my BigDecimal calculations not working?

我在使用 Swing 取反时遇到问题,出于某种原因,我的 Big Decimal 取反和加法不起作用,我的代码可以编译,但减号和加号计算不起作用,非常感谢您的帮助。

代码段

//Convert the JLabel to a Double so we can perform negation.
diallerPanelSum =  new BigDecimal(balanceAmount.getText());

//Dont allow the Balance to go negative!
if(diallerPanelSum.compareTo(BigDecimal.ZERO)>0)
    {

        if(e.getSource()==buttonMakeCall)
        {
            diallerPanelSum.subtract(new BigDecimal("1.0"));
        }

        if(e.getSource()==buttonSendText)
        {
            diallerPanelSum.subtract(new BigDecimal("0.10"));
        }

        if(e.getSource()==buttonTopUp)
        {
            diallerPanelSum.add(new BigDecimal("10.00"));
        }

    }

//Convert the Float back to a JLabel
balanceAmount.setText(String.valueOf(diallerPanelSum));

BigDecimals 是不可变的。因此,您必须再次将 add()subtract() 等操作的结果分配给 BigDecimal,因为它们会产生 new BigDecimal .试试这个:

if (diallerPanelSum.compareTo(BigDecimal.ZERO) > 0)
{

    if (e.getSource() == buttonMakeCall)
    {
        diallerPanelSum = diallerPanelSum.subtract(BigDecimal.ONE);
    }

    if (e.getSource() == buttonSendText)
    {
        diallerPanelSum = diallerPanelSum.subtract(new BigDecimal("0.10"));
    }

    if (e.getSource() == buttonTopUp)
    {
        diallerPanelSum = diallerPanelSum.add(BigDecimal.TEN);
    }

}