Search code examples
swiftnumber-formattingnsnumberformatter

Avoiding non breaking space using NumberFormatter


I have a NumberFormatter setup like the following:

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.groupingSeparator = "."
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale(identifier: "it_IT")
currencyFormatter.currencySymbol = ""

I need to retrieve a value based on a string value as input.

currencyFormatter.number(from: "1.000,00") // nil
currencyFormatter.number(from: "1.000,00\u{00a0}") // 1000

In the first sample, the formatter returns nil, while in the second I obtain the correct value (\u{00a0} is the non breaking space symbol).

Is there a way to make the first sample working without adding the space symbol?


Solution

  • If there is no currency symbol, this number formatter's style needs to be .decimal, not .currency. This is sufficient:

    let currencyFormatter = NumberFormatter()
    currencyFormatter.numberStyle = .decimal
    currencyFormatter.locale = Locale(identifier: "it_IT")