p0ny
p0ny

Reputation: 317

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?

Upvotes: 2

Views: 86

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59536

You can use NSNumberFormatter 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

Upvotes: 2

user5104686
user5104686

Reputation:

You can use an NSCharacterSet to root out those characters, like this:

var dollarStr = "$1.50"
var yuanStr = "¥18.25"
var euroStr = "20.75 €"

let strArray = [dollarStr, yuanStr, euroStr]

let charSet = NSCharacterSet(charactersInString: "$¥€ ")

for str in strArray {
    let trimmedStr = str.stringByTrimmingCharactersInSet(charSet)
    print(trimmedStr)
}

prints out :

1.50
18.25
20.75

Upvotes: 0

Related Questions