Stop using String(format:) for money

Text(price, format: .currency(code:)) formats money for the reader's locale: symbol, separators and decimals included.

iOS 16+macOS 13+ Swift 5.9

String(format: "£%.2f", price) looks fine on your Mac and wrong almost everywhere else. The symbol is hard-coded, the decimal separator is always a full stop, and there is no grouping. SwiftUI’s Text takes a FormatStyle instead, and gets all of that right for the reader.

PriceView.swift
import SwiftUI

struct PriceView: View {
    let price: Decimal = 1234.5

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // £1,234.50 in the UK, 1.234,50 £ in Germany
            Text(price, format: .currency(code: "GBP"))

            // The same style inside a sentence
            Text("Total: \(price, format: .currency(code: "EUR"))")

            // Whole pounds only
            Text(price, format: .currency(code: "GBP").precision(.fractionLength(0)))

            // The reader's own currency
            Text(price, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
        }
        .font(.title2.monospacedDigit())
    }
}

#Preview("United Kingdom") {
    PriceView()
        .environment(\.locale, Locale(identifier: "en_GB"))
}

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

Outside a view, the same style works with .formatted(_:):

let label = price.formatted(.currency(code: "GBP"))   // "£1,234.50"

How it works

Gotchas

See also