Search code examples
swiftstringnumber-formattingnsnumber

Why NSNumber do not respect locale decimalSeparator


I am using NumberFormatter to convert String to NSNumber with respect of the current locale.

My test locale is Sweden.

So the decimalSeparatorin my case is ","

This is NumberFormatter declaration.

let numberFormatter = NumberFormatter()
numberFormatter.locale = .current
numberFormatter.numberStyle = .decimal
numberFormatter.isLenient = true

Usage.

let number = numberFormatter.number(from:"1,01") // 1.01

But when I try to convert NSNumber back to string.

let stringNumber = number?.stringValue // 1.01

I receive wrong locale decimalSeparator.


Solution

  • Don't use stringValue to convert the number back to a string you wish to display to the user. Use your NumberFormatter to convert the number to a locale friendly string representation.

    FYI - there is no need to set the number formatter's locale to .current since that is the default.