Using the NumberFormatter Class

When you’re working with numbers, you may want to convert the number to a string. The simplest way to convert a number to a string is to use the String data type to convert a number to a string like this:

var aNumber = 76
String(aNumber)     // aNumber = "76"

A fancier way to convert a number to a string is to use the NumberFormatter class. At the simplest level, the NumberFormatter class just duplicates the String data type conversion like this:

var myNumber = NumberFormatter()

let costString = myNumber.string(from: 24)
print (costString!)

In the above code, the first line creates an object (myNumber) from the NumberFormatter class.

The second line converts a number (24) to a string and then stores that number into a constant named costString (“24”).

The NumberFormatter class can also convert a string into a number such as turning “9.4” into 9.4 like this:

var newStuff = myNumber.number(from: "9.4")

In this example, the line converts the string “9.4” into a number (9.4) and stores it into the newStuff variable.

Of course, you could just use the Double data type to convert a string into a number like this:

var decimal = "4.2"
Double(decimal)!

The first line creates a string variable that contains “4.2” as its value. The second line then uses the Double data type to convert the string from “4.2” to 4.2 as a Double value.

Up until this point, the NumberFormatter class simply duplicates the String and Double keywords to convert a number to a string or a string to a number. What makes the NumberFormatter class unique is that it offers the ability to spell out a number:

var myNumber = NumberFormatter()
myNumber.numberStyle = .spellOut

var x = myNumber.string(from: 742.409)

The first line defines an object called myNumber based on the NumberFormatter class. Then the second line defines the numberStyle property as .spellOut, which means it converts a number into actual words.

The third line above creates a string from the number 742.409 but spells this out as the string “seven hundred forty-two point four zero nine”, which it stores into the variable x.

The NumberFormatter class is just one of those oddball classes that you may find useful once in a while, so experiment with the NumberFormatter in a Swift playground and see how it works for yourself.

May 30th, 2017 by
HTML Snippets Powered By : XYZScripts.com