Swift – NSNumberFormatter

At some point you will find yourself in need of formatting numbers. This could be for time, temperature, currency, or just wanting to control the number of decimal places. You might even want to convert numerals to words. The NSNumberFormatter does all of this.

Figure this is a very common task so, someone will have made a library of code to handle it. The Cocoa Touch framework provides the end all in number formatting  in NSNumberFormatter.

Using the NSNumberFormatter is easy though, maybe, not intuitive until you work with it a few times.

The steps are easy:

  1. Make an instance of the NSNumberFormatter.
  2. Set options…
  3. Call the formatter.stringFromNumber() method.

A use case might look like this:

 

 

The example above creates a number formatter that converts a value into a currency style. NSNumberFormatter, in this case, should convert “cost” into currency formatted number for the current locale.

This is very sophisticated, and powerful, for very little work on our part.

The second step is where things get hazy. There are many options you can choose from. We can break these down into styles, and options.

You can think of styles as predetermined, standardized ways of expressing numbers, and options as the details that might make up a style.

For example a style might be currency style. This might include options for rounding to two decimal places, and adding a comma every third significant digit, while preceding everything with the correct currency symbol.

Options on the other hand, would things like setting the number of digits before the decimal point, and the number of digits after the decimal point. Setting the character used for the separator, like the “.”, or “,”.

Here are a few examples: