Search code examples
swiftnsnumberformattercurrency-formatting

Parse string with currency symbol and value


I am trying to parse a list of input strings from an Excel file that can have a 'currency' value, and it could be in any currency. For e.g.

  • $200
  • £300
  • €200
  • CA$300

What's the best way to parse out the currency symbol and the numeric value? I'm trying to do this with a NumberFormatter but it doesn't work for the 'euro' or the 'CAD' value.

Here is my code:

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.maximumFractionDigits = 2

let trimmedString = String(currencyString.filter { String($0).rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789.,")) == nil }).trimmingCharacters(in: .whitespacesAndNewlines)

if trimmedString.count > 0 && Locale.current.currencySymbol != trimmedString {
    // Currency symbol is *not* local currency, so lookup the locale for it
    let allLocales = Locale.availableIdentifiers.map({Locale(identifier: $0)})
    if let localeForSymbol = allLocales.filter({$0.currencySymbol == trimmedString}).first {
        currencyFormatter.locale = localeForSymbol
    }
}

if let numberValue = currencyFormatter.number(from: currencyString) {
    print ("\(NSDecimalNumber(decimal: numberValue.decimalValue))")
}

What am I getting wrong here? Or is this not possible without using some regex expressions?


Solution

  • you could try this "...to parse out the currency symbol and the numeric value":

    let currencyString = "CA$300"
    
    let valueString = currencyString.filter {
        CharacterSet(charactersIn: "0123456789.,").isSuperset(of: CharacterSet(charactersIn: String($0)))
    }.trimmingCharacters(in: .whitespacesAndNewlines)
    print("---> valueString: \(valueString) ")
    
    let symbol = currencyString.replacingOccurrences(of: valueString, with: "")
    print("---> symbol: \(symbol)")