How to localize the numbers in iOS?

Hi

In my app I am hanling the app localization programatically. To handle this I made the strings file accrording to the languages. It is working fine. Now I just want to convert the numbers (Int,Float) etc according to the selected language.

Please let me know how can I achieve this? I know that from NSNumberFormatter nubmers can be formatted but not for the particular language.

Thanks

Gopal Devra

Replies

NSNumberFormatter has a

locale
property, and a locale is a set of formatting rules that includes a specific language. For example:
import Foundation

let nf = NumberFormatter()
nf.numberStyle = .spellOut
nf.locale = Locale(identifier: "en_US")
print(nf.string(from: 123)!) // prints "one hundred twenty-three"
nf.locale = Locale(identifier: "de_DE")
print(nf.string(from: 123)!) // prints "ein?hundert?drei?und?zwanzig"

Keep in mind that a locale is more than just a language. Different locales will format the same number in different types. For example, Mexico uses Anglo-style number formatting while Spain uses the European style.

import Foundation

let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.locale = Locale(identifier: "es_ES")
print(nf.string(from: 1234)!) // prints "1.234"
nf.locale = Locale(identifier: "es_MX")
print(nf.string(from: 1234)!) // prints "1,234"

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"