Created
September 6, 2022 19:46
-
-
Save lukepistrol/bfe76666fd7c05f61932c90628c224ad to your computer and use it in GitHub Desktop.
Large Integer Formatter (K,M,B,…) Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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