Search code examples
swiftnsnumberformatter

How can I convert a currency string to a number ignoring separators?


I have a NumberFormatter (called currencyFormatter) which is configured to convert a String, such as "£1,000" to the NSDecimalNumber 1000 using the following code:

// Configuration
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "GBP"

// Usage
currencyFormatter.number(from: "£1,000")

If I omit the commas from the string the conversion still works but, if the commas as misplaced ("£10,00" for example), the method fails, returning nil.

While I could remove all the commas, this would cause issues in locales which use a comma as the decimal separator and the period in place of the comma.

Is there a safe way I can loosen the requirements of the thousands-separator (commas, periods or whatever character any other currency might use) placement in the NumberFormatter slightly but without allowing unreasonable conversion?

Many thanks in advance.


Solution

  • If your intention is to be lenient on the placements of the grouping separator (which can be a comma or a period, depending on the locale) then you could remove the formatters currencyGroupingSeparator from the input string instead of a hard-coded comma:

    var input = "£10,00"
    if let sep = currencyFormatter.currencyGroupingSeparator {
        input = input.replacingOccurrences(of: sep, with: "")
    }