p0ny p0ny - 1 year ago 99
Swift Question

Elegant way of stripping string of currency characters?

Currently Im receiving a string from a service that contains currency characters (Ex. "$123.44", "123,44 €"). I would like to strip these stings of their currency characters in order to perform some calculations on these prices (adding money, subtracting money...etc).

I know I could replace occurrences of certain characters and then re-add them later after the calculations, but I get the impression that there might be a better solution out there.

Any ideas?

Answer Source

You can use NSNumber formatter to convert a formatted price into a Double value

func getNumber(formattedPrice: String, localeID: String) -> Double? {
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    formatter.locale = NSLocale(localeIdentifier: localeID)
    return formatter.numberFromString(formattedPrice)?.doubleValue

but you'll need to specify the locale

getNumber("$123.44", localeID: "en_US") // 123.44
getNumber("123,44€", localeID: "it_IT") // 123.44
getNumber("£123.44", localeID: "en_UK") // 123.44
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download