Last active
February 28, 2023 05:53
-
-
Save marlonjames71/45c41898d3660911cfd76899882419b1 to your computer and use it in GitHub Desktop.
Swift's formatting abilities are insanely good. I have created my own implementation of this formatting style not knowing that this API existed. I just learned about this yesterday (2023-02-26). Here's a fantastic resource all about Swift's formatting abilities: [Fucking Format Style](https://fuckingformatstyle.com/).
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
import Foundation | |
// This is so I didn't have to repeat myself for all of the for loops below. | |
extension FormatStyle where Self == IntegerFormatStyle<Int> { | |
static func compactCount(significantDigits digits: Int = 3) -> Self { | |
.number.precision(.significantDigits(digits)).notation(.compactName) | |
} | |
} | |
// OR | |
let compact1 = number.formatted(.number.notation(.compactName)) | |
let compact2 = number.formatted(.number.precision(.significantDigits(3)).notation(.compactName)) | |
let likeCounts: [Int] = [ | |
37727, | |
802, | |
80382, | |
9903293, | |
7392083, | |
39302292922, | |
7839900222, | |
892640238 | |
] | |
// ------------------------------------------------------------- | |
for number in likeCounts { | |
print(number.formatted(.compactCount())) | |
} | |
/* PRINTS: | |
37.7K | |
802 | |
80.4K | |
9.90M | |
7.39M | |
39.3B | |
7.84B | |
893M | |
*/ | |
// ------------------------------------------------------------- | |
for number in likeCounts { | |
print(number.formatted(.compactCount(significantDigits: 0))) | |
} | |
/* PRINTS: | |
38K | |
802 | |
80K | |
9.9M | |
7.4M | |
39B | |
7.8B | |
893M | |
*/ | |
// ------------------------------------------------------------- | |
for number in likeCounts { | |
print(number.formatted(.compactCount(significantDigits: 1))) | |
} | |
/* PRINTS: | |
40K | |
800 | |
80K | |
10M | |
7M | |
40B | |
8B | |
900M | |
*/ | |
// ------------------------------------------------------------- | |
for number in likeCounts { | |
print(number.formatted(.compactCount(significantDigits: 4))) | |
} | |
/* PRINTS: | |
37.73K | |
802.0 | |
80.38K | |
9.903M | |
7.392M | |
39.30B | |
7.840B | |
892.6M | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment