Swift Apprentice 2.0 - small error in bank account code

In Swift Apprentice 2.0 Chapter 19 page 283 there’s an error in the bank account code (nb. Dollars is a typeAlias of Double):

func withdraw(amount: Dollars) {
    if amount > balance {
      balance -= amount
    } else {
      balance = 0 
    }
}

You can’t withdraw more than your balance in your account! The if statement should be:

if amount <= balance {

Just thinking about it, Dollars should probably be declared as its own type - a floating point number with exactly 2 decimal places to ensure partial cents are not being stored in balance or used in transactions.
Anyone know how to create such a type? A simple way it to record all money amounts in cents (as an Int) but that could get a bit messy. I’d prefer a type to store as a float value with exactly 2 decimal places.

Thank you for the heads up - much appreciated! We will definitely fix this error, bug and typo in the chapter’s updated book version for Swift 4 after all for sure and for good indeed.

You can use the NumberFormatter class in order to constrain a floating point value to a certain number of fractional digits like this:

let balance = 12.34567
let number = NSNumber(value: balance)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let string = formatter.string(from: number) // "$12.34"

Note: You have to import the Foundation framework in order to work with the NumberFormatter class as follows:

import Foundation

Please let me know if you have any other questions or issues regarding all of this.