In this example, we have shared Precision String Format Specifier In Swift? Use the following swift example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 |
I think this is the most Swift-like solution, tying the formatting operations directly to the data type. It may well be that there is a built-in library of formatting operations somewhere, or maybe it will be released soon. Keep in mind that the language is still in beta.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.