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.
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
.percenton aDoublemultiplies by 100, so 0.256 shows as 25.6%. The locale decides the separator and where the sign goes..precision(.fractionLength(2))fixes the number of decimal places: 2.5 shows as 2.50. Use a range such as.fractionLength(0...2)to drop trailing zeros instead..precision(.significantDigits(3))keeps three meaningful digits whatever the size of the number..sign(strategy: .always())adds a plus sign to positive values, which makes changes easier to read.
Gotchas
.percenton an integer does not multiply:Text(25, format: .percent)shows 25%. Mixing integers and doubles is the most common source of 2,500% bugs.- Rounding uses the standard rule for halves. Add
.rounded(rule: .down)when you must never overstate a value, such as storage left. .grouping(.never)removes thousands separators for things like years or IDs that are numbers but not quantities.