Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Localize Numbers in SwiftUI
Written by Team Kodeco

Localization doesn’t stop with text; it also applies to numerical values. Depending on the locale, numbers can be formatted differently. For instance, the United States uses periods as decimal separators and commas for thousand separators (for example, 1,000.00), while many European countries use commas as decimal separators and periods for thousand separators (for example, 1.000,00). Localizing numbers ensures that your application is user-friendly for a global audience.

SwiftUI enables you to easily localize numbers by leveraging the NumberFormatter class in the Foundation framework.

Here’s a practical example of localizing a number with a Picker allowing users to choose the locale:

struct ContentView: View {
  let numberToLocalize: Double = 12345.67
  let locales = ["en", "de", "fr"]
  @State private var selectedLocaleIndex = 0

  var localizedNumber: String {
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    numberFormatter.locale = Locale(identifier: locales[selectedLocaleIndex])
    return numberFormatter.string(from: NSNumber(value: numberToLocalize)) ?? ""
  }

  var body: some View {
    VStack(spacing: 20) {
      Text("Number: \(numberToLocalize)")
        .font(.title)

      Text("Localized: \(localizedNumber)")
        .font(.title)

      Picker("Locale", selection: $selectedLocaleIndex) {
        ForEach(0 ..< locales.count, id: \.self) {
          Text(locales[$0])
        }
      }
      .pickerStyle(.segmented)
      .padding()
    }
    .padding()
  }
}

Here’s what your preview should look like:

Localize numbers in SwiftUI.
Localize numbers in SwiftUI.

In this example, you’ve defined a number to be localized (numberToLocalize) and an array of locales. A Picker is used to allow the user to select the desired locale. The selected locale index is stored in a state variable (selectedLocaleIndex).

The localizedNumber computed property uses NumberFormatter to format numberToLocalize according to the selected locale. The formatter’s number style is set to .decimal for typical decimal numbers.

As the user switches the locale using the Picker, the number is reformatted and displayed in a localized format, adhering to the conventions of the chosen locale. This way, the number format adapts to the users’ preferences, enhancing the app’s usability and making it more inclusive.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.