Formatting input for currency with NSNumberFormatter in Swift
Here's an example on how to use it on Swift 3.( Edit: Works in Swift 5 too )
let price = 123.436 as NSNumberlet formatter = NumberFormatter()formatter.numberStyle = .currency// formatter.locale = NSLocale.currentLocale() // This is the default// In Swift 4, this ^ was renamed to simply NSLocale.currentformatter.string(from: price) // "$123.44"formatter.locale = Locale(identifier: "es_CL")formatter.string(from: price) // $123"formatter.locale = Locale(identifier: "es_ES")formatter.string(from: price) // "123,44 €"
Here's the old example on how to use it on Swift 2.
let price = 123.436let formatter = NSNumberFormatter()formatter.numberStyle = .CurrencyStyle// formatter.locale = NSLocale.currentLocale() // This is the defaultformatter.stringFromNumber(price) // "$123.44"formatter.locale = NSLocale(localeIdentifier: "es_CL")formatter.stringFromNumber(price) // $123"formatter.locale = NSLocale(localeIdentifier: "es_ES")formatter.stringFromNumber(price) // "123,44 €"
Swift 3:
If you are looking for a solution that gives you:
- "5" = "$5"
- "5.0" = "$5"
- "5.00" = "$5"
- "5.5" = "$5.50"
- "5.50" = "$5.50"
- "5.55" = "$5.55"
- "5.234234" = "5.23"
Please use the following:
func cleanDollars(_ value: String?) -> String { guard value != nil else { return "$0.00" } let doubleValue = Double(value!) ?? 0.0 let formatter = NumberFormatter() formatter.currencyCode = "USD" formatter.currencySymbol = "$" formatter.minimumFractionDigits = (value!.contains(".00")) ? 0 : 2 formatter.maximumFractionDigits = 2 formatter.numberStyle = .currencyAccounting return formatter.string(from: NSNumber(value: doubleValue)) ?? "$\(doubleValue)"}
I have implemented the solution provided by @NiñoScript as an extension as well:
Extension
// Create a string with currency formatting based on the device locale//extension Float { var asLocaleCurrency:String { var formatter = NSNumberFormatter() formatter.numberStyle = .CurrencyStyle formatter.locale = NSLocale.currentLocale() return formatter.stringFromNumber(self)! }}
Usage:
let amount = 100.07let amountString = amount.asLocaleCurrencyprint(amount.asLocaleCurrency())// prints: "$100.07"
Swift 3
extension Float { var asLocaleCurrency:String { var formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self)! }}