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.

CountsView.swift
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

Gotchas

See also