user6598297
user6598297

Reputation: 1

BigDecimal for calculation

How can I update a BigDecimal field. Like

static BigDecimal balance;

void updateBalance(BigDecimal increment){
balance= new BigDecimal ("0.00");
balance.add(increment);
}

BigDecimal getBalance(){
return balance;
}

Upvotes: 0

Views: 131

Answers (1)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12781

Similar to String, the BigDecimal class is immutable. Every operation (plus, multiply etc.) returns a new instance, rather than updating the instance you have.

In your case, you would need to write something like this:

private BigDecimal balance = BigDecimal.ZERO;

public void addToBalance(BigDecimal increment) {
    balance = balance.add(increment);
}

public BigDecimal getBalance() {
    return balance;
}

Upvotes: 1

Related Questions