Zack Shapiro
Zack Shapiro

Reputation: 6998

NumberFormatter not working correctly

I'm decoding a string version of a decimal that I want to be formatted and returned as a Double:

let str = "0.945404"
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.roundingMode = .halfUp
numberFormatter.numberStyle = .decimal

print(numberFormatter.number(from: str))

numberFormatter.number(from: str) seems to return nil and I can't figure out why.

Would love any help here. Thanks

Upvotes: 2

Views: 1689

Answers (2)

Adriana
Adriana

Reputation: 235

FYI: This issue only happened to me when testing on the device, on the simulator the formatter was I guess picking up the US locale (Although i have localisation activated and it was meant to be German).

Upvotes: 0

rmaddy
rmaddy

Reputation: 318814

If you are getting a fixed format decimal string then you need to setup your number formatter with a matching locale. Without doing so the formatter assumes the user's locale and many locales do not use the . as the decimal separator.

There is also no need to set the fraction digits when converting a string to a number. Later, when displaying the number to a user you can use another number formatter (using the user's locale this time) with a desired number of fraction digits to get a displayable string.

let str = "0.945404"
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en_US")
numberFormatter.numberStyle = .decimal

print(numberFormatter.number(from: str))

Upvotes: 4

Related Questions