Amrit Sidhu
Amrit Sidhu

Reputation: 1950

NumberFormatter in xcode 11

I have been struggling since last few hours. My code was working in xcode 10.XX. After I updated to xcode 11, the numberFormatter stopped working and now I connot get a number from a string value. The below code gives me 552 € in xcode 10 and nil in xcode 11. Can anyone help me recognize what the problem is?

    let currencyFormatter = NumberFormatter()
    currencyFormatter.usesGroupingSeparator = true
    currencyFormatter.numberStyle = .currency

    currencyFormatter.locale = Locale(identifier: "de_DE")
    if let priceString = currencyFormatter.number(from: "552") {
        print(priceString) // Should Display 552 € in the German locale
    }

Upvotes: 0

Views: 372

Answers (1)

André Slotta
André Slotta

Reputation: 14030

The problem is that you are using a NumberFormatter with a numberStyle of currency to convert a string containing a regular number – "552" – which is not a currency string. That does not work.

You have to use the decimal style to convert the string to a number. Afterwards you can use the currency style to convert the number back to a string.

let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "de_DE")

// string to number
formatter.numberStyle = .decimal
if let n = formatter.number(from: "552") {
    print(n) // prints "552"

    // number to string (formatted as currency)
    formatter.numberStyle = .currency
    if let s = formatter.string(from: n) {
        print(s) // prints "552,00 €"
    }
}

Upvotes: 1

Related Questions