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.
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
.currency(code:)takes the currency from the ISO code and everything else from the locale: where the symbol goes, the grouping separator and the decimal separator.Text(_:format:)and the\(value, format:)interpolation use the locale in the SwiftUI environment, so a preview with.environment(\.locale, ...)shows exactly what a reader in that region sees.- The currency also sets the number of decimals. Yen has none, so 1234.5 in JPY shows as ¥1,234 (JP¥1,234 in the UK): halves round to the even number by default.
- Style modifiers chain:
.precision(.fractionLength(0)),.rounded(rule: .down)and.presentation(.isoCode)for “GBP 1,234.50”.
Gotchas
- Use
Decimalfor money.Doublecannot store 0.1 exactly, and the errors show up once you start adding prices together. - Pass the currency the amount is actually in. The locale only decides how it looks; formatting a price in pounds with the reader’s currency code turns £10 into $10.
Locale.current.currencyneeds iOS 16 or macOS 13. On earlier systems useLocale.current.currencyCode.- The output contains non-breaking spaces in many locales, so compare formatted strings in tests with care.