Skip to content

Instantly share code, notes, and snippets.

@marlonjames71
Last active February 9, 2023 07:51
Show Gist options
  • Save marlonjames71/3fa14420193f50858a9ea3f5d864c410 to your computer and use it in GitHub Desktop.
Save marlonjames71/3fa14420193f50858a9ea3f5d864c410 to your computer and use it in GitHub Desktop.
This methods is for formatting numbers so they're shortened and shown with K for thousands, M for millions, and B for billions.
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
func shorten(_ number: Int, afterDigitPlacement placement: Int = 3) -> String {
let symbols = ["K", "M", "B"]
let placementCount = String(number).count
guard placementCount > placement else { return number.formatted() }
let offset = Float((placementCount - 1) / 3)
let divisor = pow(1000, offset)
let shortened = Float(number) / Float(divisor)
let symbol = symbols[safe: Int(offset)-1] ?? ""
let shortenedString = String(format: "%3.1f%", shortened)
return shortenedString.replacingOccurrences(of: ".0", with: "") + symbol
}
print(shorten(158)) // 158
print(shorten(1562)) // 1.6K
print(shorten(1562, afterDigitPlacement: 4)) // 1,562
print(shorten(10236)) // 10.2K
print(shorten(10645)) // 10.6K
print(shorten(12045)) // 12K
print(shorten(126548)) // 126.5K
print(shorten(2115647)) // 2.1M
print(shorten(21506322)) // 21.5M
print(shorten(212506322)) // 212.5M
print(shorten(21506322344)) // 21.5B
print(shorten(215063223443)) // 215.1B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment