Skip to content

Instantly share code, notes, and snippets.

@lawrenceching
Created June 3, 2016 04:43
Show Gist options
  • Save lawrenceching/1990e34d9b0c6438df01271c0f8b757c to your computer and use it in GitHub Desktop.
Save lawrenceching/1990e34d9b0c6438df01271c0f8b757c to your computer and use it in GitHub Desktop.
Format the number, turn 3 into 3.00 or 033
import Foundation
extension Int {
func format(f: String) -> String {
return String(format: "%\(f)d", self)
}
}
extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
let someInt = 4, someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004
let someDouble = 3.14159265359, someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment