update: Xcode 8.2.1 • Swift 3.0.2. You can use NumberFormatter () to convert your string to a number. You just need to specify decimalSeparator as follows:
extension String { static let numberFormatter = NumberFormatter() var doubleValue: Double { String.numberFormatter.decimalSeparator = "." if let result = String.numberFormatter.number(from: self) { return result.doubleValue } else { String.numberFormatter.decimalSeparator = "," if let result = String.numberFormatter.number(from: self) { return result.doubleValue } } return 0 } } "2.25".doubleValue
Currency formatting should also be done using NumberFormat, so create a read-only computed currency that extends the FloatingPoint protocol to return a formatted string from the String doubleValue property.
extension NumberFormatter { convenience init(style: Style) { self.init() self.numberStyle = style } } extension Formatter { static let currency = NumberFormatter(style: .currency) } extension FloatingPoint { var currency: String { return Formatter.currency.string(for: self) ?? "" } }
let costString = "2,25".doubleValue.currency // "$2.25"
Formatter.currency.locale = Locale(identifier: "en_US") "2222.25".doubleValue.currency // "$2,222.25" "2222,25".doubleValue.currency // "$2,222.25" Formatter.currency.locale = Locale(identifier: "pt_BR") "2222.25".doubleValue.currency // "R$2.222,25" "2222,25".doubleValue.currency // "R$2.222,25"
source share