Format Measurements Without Hardcoding Units

A route planner stores distance in meters. One screen divides by 1,000 and appends “km.” Another uses a formatter that changes kilometers to miles for a US locale. A third rounds the model value before saving it.

All three screens started with the same distance. They ended up with three different ideas about who controls its presentation.

Separate three decisions

The stored quantity needs a known unit. The product needs a policy for choosing display units. The formatter needs a locale for decimal separators, spacing, and unit wording.

An explicit “Always show kilometers” preference should survive a locale change. An “Automatic” preference should allow locale-appropriate units. Neither should rewrite the original measurement.

Foundation’s measurement format style combines unit presentation with number formatting. Its usage setting distinguishes contextual formatting from keeping the provided unit.

Here is a distance label with that distinction made explicit:

import Foundation

enum DistancePreference { case automatic, kilometers, miles }

func distanceLabel(meters: Double, preference: DistancePreference, locale: Locale) -> String? {
    guard meters.isFinite, meters >= 0 else { return nil }
    let distance = Measurement(value: meters, unit: UnitLength.meters)
    let number = FloatingPointFormatStyle<Double>.number.precision(.fractionLength(0...1))
    switch preference {
    case .automatic:
        return distance.formatted(
            .measurement(
                width: .abbreviated, usage: .road,
                numberFormatStyle: number
            ).locale(locale))
    case .kilometers:
        return distance.converted(to: .kilometers).formatted(
            .measurement(
                width: .abbreviated, usage: .asProvided,
                numberFormatStyle: number
            ).locale(locale))
    case .miles:
        return distance.converted(to: .miles).formatted(
            .measurement(
                width: .abbreviated, usage: .asProvided,
                numberFormatStyle: number
            ).locale(locale))
    }
}

Convert before asking to keep the unit

The kilometers branch first converts the quantity to kilometers, then uses .asProvided. That means “keep kilometers,” because kilometers is now the provided unit.

Applying .asProvided directly to the original measurement would keep meters. It does not mean “respect whichever unit my settings screen happens to show.” The code has to connect the preference to the quantity it passes to the formatter.

The automatic branch uses .road because this is a route distance. Context matters: a person’s height and a road distance should not necessarily use the same presentation policy. Choose usage for the quantity the user is reading, not for whichever sample happened to compile first.

Round the label, not the model

The number style limits the displayed fractional precision. The underlying meters value is untouched, so later calculations, exports, and unit changes still use the original measurement.

If you persist 1.6 after displaying 1,609.344 meters as kilometers, converting that rounded value back to miles introduces avoidable error. Repeated changes between units can make that error worse.

A displayed distance also has an accuracy contract. Showing six fractional digits does not make a rough location estimate precise. Choose the label’s precision with the data source and product context in mind; the example’s one decimal place is a presentation choice for this route label.

Do not parse your own label back into storage

A formatted string may contain a localized decimal separator, a nonbreaking space, and a translated unit. Splitting on an ASCII space or calling Double(label) is not a reliable inverse.

Keep numeric editing separate from the read-only label. If a settings field lets someone type miles, parse that field with a locale-aware numeric strategy, associate it with the selected unit, and convert the accepted measurement to your canonical storage unit. Do not use the display label as a hidden serialization format.

The helper rejects negative and nonfinite values because this particular domain represents a nonnegative route length. Other measurements, such as temperatures or elevation differences, legitimately allow negative values. Validation belongs to the domain rather than a generic “all measurements must be positive” utility.

Test the preference and the locale independently

Use a known conversion: 1,609.344 meters is one mile. With the explicit mile preference, the English label should remain in miles. With explicit kilometers, both US and French formatting should retain kilometers while their decimal presentation differs.

Avoid making every test depend on an exact whitespace character. Exact snapshot strings are useful for a controlled OS version, but semantic checks for the requested unit and expected rounded number explain failures more clearly across formatter-data updates.

September 2026 review: the Swift 6.4 executable passed explicit mile/kilometer conversion, US/French decimal formatting, zero, and invalid-input checks. On this system the kilometer labels were 1.6 km and 1,6 km. Automatic unit choices and additional locales should be reviewed against the product’s intended usage.

A unit preference is a user decision. A locale is a formatting context. Keeping them separate makes both easier to honor.