Skip to content

Instantly share code, notes, and snippets.

@lukepistrol
Created September 6, 2022 19:46
Show Gist options
  • Save lukepistrol/bfe76666fd7c05f61932c90628c224ad to your computer and use it in GitHub Desktop.
Save lukepistrol/bfe76666fd7c05f61932c90628c224ad to your computer and use it in GitHub Desktop.
Large Integer Formatter (K,M,B,…) Swift
struct AbbreviatedIntegerStyle: FormatStyle {
typealias FormatInput = Int
typealias FormatOutput = String
func format(_ value: Int) -> String {
let absolute = abs(value)
let number = Double(value)
func rnd(_ number: Double) -> String {
(round(number*10)/10).formatted()
}
switch absolute {
case 1_000_000...: return rnd(number / 1_000_000) + "M"
case 1_000...: return rnd(number / 1_000) + "K"
default: return "\(value)"
}
}
}
extension FormatStyle where Self == AbbreviatedIntegerStyle {
static var abbreviatedInt: AbbreviatedIntegerStyle { .init() }
}
print(1000000.formatted(.abbreviatedInt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment