Skip to content

Instantly share code, notes, and snippets.

@mredig
Created October 2, 2019 15:52
Show Gist options
  • Save mredig/8a7cde1fe6016808e4bf6454261f8973 to your computer and use it in GitHub Desktop.
Save mredig/8a7cde1fe6016808e4bf6454261f8973 to your computer and use it in GitHub Desktop.
func makeChangeAsString(fromAmount amount: Double, withCost cost: Double) -> String {
let change = amount - cost
let dollars: Int
var changeRemaining: Double = 0
(dollars, changeRemaining) = getCoinCount(1.0, fromChange: change)
let quarters: Int
(quarters, changeRemaining) = getCoinCount(0.25, fromChange: changeRemaining)
let dimes: Int
(dimes, changeRemaining) = getCoinCount(0.1, fromChange: changeRemaining)
let nickels: Int
(nickels, changeRemaining) = getCoinCount(0.05, fromChange: changeRemaining)
let pennies = Int(changeRemaining * 100)
return "Your change is $\(change). That's \(dollars) dollars, \(quarters) quarters, \(dimes) dimes, \(nickels) nickels, and \(pennies) pennies."
}
func getCoinCount(_ valueCount: Double, fromChange change: Double) -> (coinCount: Int, changeRemaining: Double) {
guard change > 0 else { return (0,0) }
let pennyCountDesired = Int(valueCount * 100)
let currentPennyCount = Int(change * 100)
let coinCount = currentPennyCount / pennyCountDesired
let remainingPCount = currentPennyCount % pennyCountDesired
let changeRemaining = Double(remainingPCount) / 100
return (coinCount, changeRemaining)
}
print(makeChangeAsString(fromAmount: 5.00, withCost: 2.15))
print(makeChangeAsString(fromAmount: 10.00, withCost: 2.38))
print(makeChangeAsString(fromAmount: 10.00, withCost: 2.33))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment