Problem

What gets logged?

class BankAccount {
  constructor(initialBalance) {
    this.balance = initialBalance;
    this.minimumBalance = 20.00;
  }

  deposit(amount) {
    this.balance += amount;
  }

  withdraw(amount) {
    if (this.balance - amount <= this.minimumBalance) {
      return false;
    } else {
      this.balance -= amount;
      return true;
    }
  }

  getBalance() {
    return this.balance;
  }
}

const myAccount = new BankAccount(150.00);
myAccount.deposit(0.10);
myAccount.deposit(0.20);

myAccount.withdraw(130.30);
console.log(myAccount.getBalance());
Solution

Answer: 150.29999999999998

We would expect to see 20.00, but due to floating point arithmetic in JavaScript, we get an unexpected result. To fix this issue, we can represent money as integers (e.g., cents) and use Math.round to avoid the pitfalls of floating-point calculations. Here is the updated code:

class BankAccount {
  constructor(initialBalance) {
    this.balanceCents = Math.round(initialBalance * 100);
    this.minimumBalanceCents = 2000;
  }

  deposit(amount) {
    this.balanceCents += Math.round(amount * 100);
  }

  withdraw(amount) {
    const withdrawalCents = Math.round(amount * 100);

    if (
      Math.round(this.balanceCents - withdrawalCents) < this.minimumBalanceCents
    ) {
      return false;
    } else {
      this.balanceCents -= withdrawalCents;
      return true;
    }
  }

  getBalance() {
    return this.balanceCents / 100;
  }
}

const myAccount = new BankAccount(150.0);
myAccount.deposit(0.1);
myAccount.deposit(0.2);
myAccount.withdraw(130.3);

// Displaying the remaining balance, should be 20.00
console.log(myAccount.getBalance());