Using NumberFormatter in Swift for Precision Issues with Fractions & More

Kelly O’
Mac O’Clock
Published in
2 min readApr 27, 2020
Photo by Mika Baumeister on Unsplash

I was creating a calculator app for my class recently when I ran into an issue. Why were some of my calculations coming out all cuckoo bananas?

For example, if I put in 2.3 x 3 I would get a result of 6.899999999 instead of 6.9.

Turns out, this is a universal problem with computer systems where some fractions cannot be stored with exact precision in a binary file system.

Thankfully, in Swift, there is an easy fix using the NumberFormatter class.

Here is the code to use. It can be placed in an extension so that it may be used for all Doubles.

Then to display the value, you use dot notation to call the function on the variable that holds the value.

displayLabel.text = newValue.computeDecimal()

Number formatter also comes in handy when working with currency!

Formatting Currency

You can even select which currency you would like to format for. By using formatter.locale = .current as above, it will format using the current location of your device. If you would like to set the currency locale, you can do so by setting the Locale identifier. For example, the code below is set for Great Britain.

formatter.locale = Locale(identifier: “en_GB”)

You can even pull in the currency symbol and set it to a label using:

currencyLabel.text = formatter.currencySymbol

This is only the tip of the iceberg of what you can do with NumberFormatter. Check out the Apple Documentation to see what else it can do!