Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make a function that takes two doubles return a string
import UIKit
func makeChangeAsString(fromAmount: Double, withCost: Double) -> String {
let change = fromAmount - withCost
let dollars = Int(change / 1)
var cents = change.truncatingRemainder(dividingBy: 1)
let quarters = Int(cents / 0.25)
cents -= Double(quarters) * 0.25
let dimes = Int(cents / 0.10)
cents -= Double(dimes) * 0.10
let nickles = Int(cents / 0.05)
cents -= Double(nickles) * 0.05
let pennies = Int(cents / 0.01)
return "Your change is \(change). That is \(dollars) dollars, \(quarters) quarters \(dimes) dimes \(nickles) nickles, \(pennies) pennies"
}
makeChangeAsString(fromAmount: 5.00, withCost: 2.15) // returns "Your change is $2.85. That is 2 dollars, 3 quarters, 1 dime, 0 nickels and 0 pennies."
makeChangeAsString(fromAmount: 10.00, withCost: 2.38) // returns "Your change is $7.62. That is 7 dollars, 2 quarters, 1 dime, 0 nickels and 2 pennies."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment