Skip to Content
Course content

71: NumberFormatter and MeasurementFormatter

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've reviewed a lot of PRs over the years, and there is one pattern that always makes me sigh: the "hardcoded format" trap. It usually looks something like this: "\(amount) kg" or String(format: "%.2f", price). It seems harmless when you're testing on your own simulator in your own timezone, but it's a ticking time bomb for your international users.

The Myth: "String Interpolation is Enough for Formatting"

The common misconception is that numbers are universal. You might think that because 1,234.56 is clear to you, it's clear to everyone. It isn't. In many European countries, the comma and the period are swapped (1.234,56), and some locales use a non-breaking space as a thousands separator.

// The "naive" way that fails in Germany or France
let balance = 1234.56
let displayString = "Your balance is $\(balance)" 
// Output: "Your balance is $1234.56" (No matter where the user lives)

If you ship this, you're telling your users that your app doesn't speak their language. Beyond just the decimal point, hardcoding symbols like "$" or "kg" is a mistake because currency symbols and unit placements vary wildly across the globe.

The Fix: Letting NumberFormatter Handle the Locale

This is where NumberFormatter comes in. Instead of you deciding where the comma goes, you tell Swift the intent of the number, and it asks the system how to render it for the current user's locale.

let formatter = NumberFormatter()
formatter.numberStyle = .currency // Handles symbol and placement automatically
formatter.locale = Locale(identifier: "de_DE") // Forcing German for this example

if let formattedPrice = formatter.string(from: 1234.56 as NSNumber) {
    print(formattedPrice) // "1.234,56 €"
}

Notice how the Euro symbol moved to the end and the separators swapped? I didn't write a single line of logic to handle that. By using .numberStyle = .currency or .decimal, you're delegating the complexity to the OS, which is exactly what you want.

Stop Manually Multiplying Units with MeasurementFormatter

Now, measurements are a whole different beast. I see developers doing math like distanceInKm * 0.621371 to get miles. Please, stop doing that. Not only is it prone to rounding errors, but it's a nightmare to maintain as you add more units.

Swift provides Measurement and MeasurementFormatter to handle this. You define the value and the unit, and the formatter handles the conversion and the localized string representation in one go.

let distance = Measurement(value: 10, unit: UnitLength.kilometers)
let formatter = MeasurementFormatter()
formatter.unitOptions = .naturalScale // Automatically chooses km vs m based on magnitude

// If the user is in the US, this automatically converts to miles
print(formatter.string(from: distance)) 
// Output (US): "6.21 miles"
// Output (France): "10 km"

The .naturalScale option is a personal favorite of mine. It ensures that if a distance is 1,500 meters, it might show up as "1.5 km" instead of a giant string of meters, depending on the locale's preferences. It makes your UI feel polished and professional without you having to write a dozen if/else statements.




📋 Practical Task

Building a Localized Health Metric Dashboard

You are building a health app that tracks a user's daily water intake and running distance. Currently, the code is hardcoded for US English, and it looks amateur. Your task is to refactor the following code to use NumberFormatter and MeasurementFormatter so that it adapts to the user's locale.

// CURRENT BROKEN CODE
let waterIntake = 2500.5 // Milliliters
let runDistance = 5.25 // Kilometers

// TODO: Refactor these prints to use proper Formatters
print("Water: \(waterIntake) ml") 
print("Distance: \(runDistance) km")

Requirements:

  • Create a NumberFormatter to display the water intake as a decimal number with no more than 1 fraction digit.
  • Create a MeasurementFormatter to display the run distance. Ensure it uses .naturalScale so that the unit is appropriate for the locale.
  • Initialize the Measurement object using UnitLength.kilometers.
  • Test your output by temporarily setting formatter.locale = Locale(identifier: "en_US") and then "fr_FR" to verify the units and separators change automatically.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.