Format percentages and decimal places

Format percentages, signs, and decimal places with format styles, and let the guest's locale choose the separators.

iOS 15+macOS 12+ Swift 5.9

Multiplying by 100 and adding a percent sign is the usual way to show a percentage, and it is wrong in much of the world: French puts a space before the sign, German uses a comma for decimals. Format styles handle percentages, precision and plus signs, and the result follows the guest’s locale.

StatsView.swift
import SwiftUI

struct StatsView: View {
    let completion = 0.256
    let growth = 0.042
    let average = 3.14159
    let visits = 1_234_567

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(completion, format: .percent)
            Text(completion, format: .percent.precision(.fractionLength(0)))
            Text(growth, format: .percent.sign(strategy: .always()))
            Text(average, format: .number.precision(.fractionLength(2)))
            Text(visits, format: .number)
        }
        .monospacedDigit()
        .padding()
    }
}

#Preview("United Kingdom") {
    StatsView()
}

#Preview("Germany") {
    StatsView()
        .environment(\.locale, Locale(identifier: "de_DE"))
}

How it works

Gotchas

See also