Compact big numbers like 1.2K and 3.4M
Show follower counts, views and downloads in short form, with the right abbreviations for each language.
iOS 16+macOS 13+ Swift 5.9
Big counts need to be short to fit in a badge or a row, and hand-written “if over a million, divide and add M” code only works in English. The compact name notation abbreviates numbers the way each language does.
import SwiftUI
struct CountsView: View {
let views = 1_234
let downloads = 3_400_000
let followers = 98_765
var body: some View {
HStack(spacing: 32) {
stat("Views", views)
stat("Downloads", downloads)
stat("Followers", followers)
}
.padding()
}
private func stat(_ label: String, _ value: Int) -> some View {
VStack {
Text(value, format: .number.notation(.compactName))
.font(.title.bold())
Text(label)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
#Preview("United States") {
CountsView()
.environment(\.locale, Locale(identifier: "en_US"))
}
#Preview("Japan") {
CountsView()
.environment(\.locale, Locale(identifier: "ja_JP"))
}How it works
.notation(.compactName)picks a unit and rounds to about two significant digits.- The abbreviations come from the locale: K and M in the US, k and m in the UK, Mio. and Mrd. in Germany, and units of ten thousand (万) in Japanese.
- It combines with other options, for example
.precision(.significantDigits(3))for 98.8K instead of 99K.
Gotchas
- Small numbers are not abbreviated, and the threshold depends on the language: German and Japanese show 1234 in full.
- Compact numbers are rounded, so pair them with the exact value somewhere, such as an accessibility label or a detail screen.
.notation(.scientific)gives 1.23456E5 for very large or very small measurements, which suits technical data better than compact names.