Today we'll continue our series on localizing our apps by looking at NSNumberFormatter.
It can help us make sure we're displaying numbers using the format a user expects in their culture or language, as well as display numbers in some fun ways. Let's get started.
First, let's see how we can take advantage of NSNumberFormatter when localizing our app.
We'll create a new formatter, and tell it to use the user's current locale. (An NSLocale is a class that encapsulates information about linguistic, cultural, and technological conventions and standards).
let formatter = NSNumberFormatter()
formatter.locale = NSLocale.currentLocale()
Now, we can set what kind of format we'd like to perform. NSNumberFormatter has a ton of great built-in styles. Let's try the Currency style:
formatter.numberStyle = .CurrencyStyle
formatter.stringFromNumber(2187.31) // "$2,187.31"
Then, we ask the formatter for a string from a number.
Apple has done all the hard work of figuring out how numbers should change when displayed in different locales. The example before showed the output from a device in the US, what about one from Germany? Let's try it:
formatter.locale = NSLocale(localeIdentifier: "de_DE")
formatter.numberStyle = .CurrencyStyle
formatter.stringFromNumber(2187.31) // "2.187,31Β β¬"
Neat! What else can NSNumberFormatter do? Here's some fun examples:
formatter.numberStyle = .SpellOutStyle
formatter.stringFromNumber(21) // "twenty-oneβ
formatter.numberStyle = .OrdinalStyle
formatter.stringFromNumber(21) // "21st"
In addition to all of that, NSNumberFormatter also has an insanely long list of customizable properties allowing us to create completely custom formatters (best done via subclassing).