How to Use NumberFormatter (NSNumberFormatter) in Swift to Make Currency Numbers Easy to Read

NSNumberFormatter Currency Price String in Swift

When you display a number in Swift (Float, Double, Int) it will display without grouping separators. By default a number like 4,592,028.0 will display like: 4592028.0 You need to use the NumberFormatter (NSNumberFormatter) class to convert your number into a pretty String for a text field.

To display currency, you will need to show the currency symbol ($, €, ¥, £) for the current locale.

Displaying the correct currency symbol can get complex pretty quickly – thankfully, Apple has you covered and provides a solution with the NSNumberFormatter, now NumberFormatter class.

NSNumberFormatter Is Now NumberFormatter in Swift 4

In Swift 4 many of these API's renamed, so I'll share the Swift 2 code, as well as the updated Swift 4 code.

NumberFormatter will show the correct symbol, and the formatting that you might not realize is very different from what you're used to. Different countries use different decimal separators and grouping separators—take a look!

  • In the USA: $3,490,000.89
  • In France: 3 490 000,89 €
  • In Germany: 3.490.000,89 €

You don't have to memorize these currency symbols, grouping separators, or decimal separators. Apple has done all the heavy lifting with NumberFormatter.

The following code sample will use the current locale of the user's device to format the currency:

Swift 4+

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current

// We'll force unwrap with the !, if you've got defined data you may need more error checking
let priceString = currencyFormatter.string(from: 9999.99)!
print(priceString) // Displays $9,999.99 in the US locale

Swift 2

var currencyFormatter = NSNumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle 
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.currentLocale()
var priceString = currencyFormatter.stringFromNumber(9999.99)
print(priceString) // Displays $9,999.99 in the US locale

NumberFormatter can use the correct separators and currency symbols for your country by setting the Locale directly.

Forcing a Custom Locale

You can override the users locale to display specific currency formats by changing the Locale using the identifier.

currencyFormatter.locale = Locale(identifier: "fr_FR")
if let priceString = currencyFormatter.string(from: 9999.99) {
    print(priceString) // Displays 9 999,99 € in the French locale
}

currencyFormatter.locale = Locale(identifier: "de_DE")
if let priceString = currencyFormatter.string(from: 9999.99) {
    print(priceString) // Displays 9.999,99 € in the German locale
}

More Locale Identifier Codes

Download the Swift Playgrounds for NumberFormatter

I've got more examples that you can explore to play with the NumberFormatter Playgrounds file.

Download the currency Playgrounds file and you can learn how to programmatically set the NSLocale to the German, French, and US English.

Homework

Try changing the NumberFormatter's groupingSeparator, currencyGroupingSeparator, and related properties to format both decimal style numbers and currency style numbers.

Read the documentation for NumberFormatter and experiment with changing how it formats your decimal numbers (i.e. try different grouping separators like: "_" or "*").

How to Create Outlets and Actions in Xcode Using Swift - Swift Tips 6

Xcode with the Assistant Editor (Venn Diagram button) let's you connect code and UI (user interface) files together.

In order for you to make your UI interactive, you need to create connections from the UI to your related code files. These connections give Xcode names that you can use in your code file to modify how something looks programmatically or to respond to user input (button tabs, sliders, switches, etc). There are two primary connections you will create in Xcode: outlets and actions.

Outlets

Outlets enable you to give a UI element a name that you can use in your code. You can create a connection from a label to your code file using an outlet.

Outlets will look like:

@IBOutlet weak var textLabel: UILabel!

You can modify properties associated with your UI element, like text and textColor for UILabel objects.

Actions

Actions let you trigger things that can happen in response to user input. When a user moves a slider, enters a date, or types their name you can run a chunk of code to respond to it.

Actions will look like:

@IBAction func buttonPressed(sender: AnyObject) {

    print("hi developer")

    textLabel.text = "you pressed me "
}

Creating Outlets and Actions

  1. Open the Assistant Editor
  2. Right-click and drag from your UI element (i.e. label) to the code file
  3. Xcode auto inserts code for you to create the name and connection

Variables and Properties

You can also create variables and properties in your Swift code files. For ViewController.swift files it is easier to initialize variables and properties when you declare them, or in your viewDidLoad() method.

Swift Tips Source Code

Grab the source code for this Swift Tip and many more at: http://SuperEasyApps.com/SwiftTips

3 Common Crashes for Beginner iPhone Developers in Xcode using Swift

3 common crashes for beginner iphone developers in xcode using swift

As you work with your first iPhone app you will inevitably run into different crashes. The three most common crashes are what every beginner encounters. If you know what to look for, you can avoid these in the future.

Two of the crashes are real crashes and one is because you clicked and mistakenly added a breakpoint, which is used for finding bugs.

Here are the three crashes and how to fix them:

  1. Breakpoint Crash

    • Problem: Thread 1: breakpoint 1.1
    • Why: You clicked in the gutter left of your code and added a blue flag.
    • Solution: Delete or disable the breakpoint (blue flag) from the code gutter.
  2. Storyboard IBOutlet Crash

    • Problem: Thread 1: signal SIGABRT
    • Console:

      Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<ViewController 0x7fbd74a090d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key spellingMistakee.'

    • Why: You deleted an Outlet/Action connection in code or renamed it (i.e. spelling mistake).

    • Solution: Right-click on the UI element and remove the old Outlet/Action connection mentioned as the key in the top of the Console output.
  3. Nil Optional Crash

    • Problem: Thread 1: EXC_BAD_INSTRUCTION
    • Console:

      fatal error: unexpectedly found nil while unwrapping an Optional value

    • Why: You removed a UIView IBOutlet connection and then used the IBOutlet variable in code. The variable has no value until you reconnect it to the UI element.

    • Solution: Right-click and drag from the UI element to the IBOutlet property that Xcode stopped at with the EXC_BAD_INSTRUCTION.