Parse string with currency symbol and value

732 Views Asked by At

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?

2

There are 2 best solutions below

0
workingdog support Ukraine On BEST ANSWER

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)")
3
flanker On

@workingdog has a valid answer. An alternative, and one I always reach for, is to use regex, where 3 simple regex can be used to identify any non-numeric leading characters, the numeric characters, and any non-numeric postfix characters:

let prefixRegex = #"^[^0-9]+"#
let numRegex = #"[0-9]+"#
let postfixRegex = #"[^0-9]+$"#

These can then be used with String's .range(of: options:) using the .regularExpression option to get the element's range, and then use that to extract the relevant SubString.

As a very quick demo of this in action:

["$20", "£300", "€200", "CA$300", "798xyz", "$123abc"]
   .forEach{string in
      var components: [Range<String.Index>?] = []
      
      components.append( string.range(of: prefixRegex, options: .regularExpression))
      components.append( string.range(of: numRegex, options: .regularExpression))
      components.append( string.range(of: postfixRegex, options: .regularExpression))
      
      print(components
         .map{ $0 != nil ? String(string[$0!]).padded(to: 8) : String(repeating: " ", count: 8) }
         .joined(separator: "")
      )
   }

This provides an output of

$       20              
£       300             
€       200             
CA$     300             
        798     xyz     
$       123     abc  

.padded(to:) is a utility extension on String that pads the rear of a string to a specified length with any character.

extension String {
   func padded(to paddedTo :Int, with padding: String = " ") -> Self {
      while count < paddedTo {
         return (self + padding).padded(to: paddedTo, with: padding)
      }
      return self
   }
}