I am trying to format UILabel text for selected locale using NSNumberFormatter for NSNumberFormatterStyle.DecimalStyle and setting up locale for the formatter as ar-SA.
When UILabel text has large numbers that are converted to E notation(scientific notation) for example- "1e9", "2.3456e24" etc. the numberFromString() returns nil for ar-SA locale. However, it works fine for other locales.
@IBOutlet weak var displayText: UILabel!
let format = NSNumberFormatter()
format.numberStyle = NSNumberFormatterStyle.DecimalStyle
format.locale = NSLocale(localeIdentifier: language)// where language = "ar-SA" or "en-US" or "de-DE"
format.maximumFractionDigits = 16
var result = displayText.text! // result = "1e9" or "2.3456e24"
guard let number = format.numberFromString(result), let string = format.stringFromNumber(number) else {
displayText.text = "Error"
return
}
result = string
How to fix this? Is there any restriction with ar-SA locale and E notations together?
You can convert the number to "en" locale and after that you convert the resulting string to "ar_SA" locale. Apparently, the "ar_SA" locale does not recognize the "e" notation.
let format = NSNumberFormatter()
format.numberStyle = NSNumberFormatterStyle.DecimalStyle
format.locale = NSLocale(localeIdentifier: "en")
format.maximumFractionDigits = 16
var result = displayText.text!
guard let number = format.numberFromString(result), let string = format.stringFromNumber(number) else {
return
}
format.locale = NSLocale(localeIdentifier: "ar_SA")
guard let string2 = format.stringFromNumber(number) else {
return
}
result = string2
If you format an NSNumber using an NSNumberFormatter with scientific style and an Arabic locale, you will see that a number such as 2.3456e24 would need to be entered as ٢٫٣٤٥٦اس٢٤.
Trying to parse 2.3456e24 will only work on locales that use the digits 0-9, a period, and e or E for the exponent.
If you wish to allow a user to enter numbers in various formats, you will need to try your number formatter with multiple locales. Start with the default locale. If that gives back a nil number, try another locale. Try as many locales as you wish to support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With