-
-
Save RobertAudi/e2e11f2f7c8aacc46c05932e6897e698 to your computer and use it in GitHub Desktop.
Convert large numbers to smaller format
This file contains hidden or 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 | |
extension Int { | |
func abbreviate() -> String { | |
typealias Abbrevation = (threshold: Double, divisor: Double, suffix: String) | |
let abbreviations: [Abbrevation] = [ | |
(0, 1, ""), | |
(1000.0, 1000.0, "K"), | |
(100_000.0, 1_000_000.0, "M"), | |
(100_000_000.0, 1_000_000_000.0, "B"), | |
(100_000_000_000.0, 1_000_000_000_000.0, "T") | |
] | |
let startValue = Double (abs(self)) | |
let abbreviation: Abbrevation = { | |
var prevAbbreviation = abbreviations[0] | |
for tmpAbbreviation in abbreviations { | |
if (startValue < tmpAbbreviation.threshold) { | |
break | |
} | |
prevAbbreviation = tmpAbbreviation | |
} | |
return prevAbbreviation | |
}() | |
let formatter = NumberFormatter() | |
formatter.positiveSuffix = abbreviation.suffix | |
formatter.negativeSuffix = abbreviation.suffix | |
formatter.allowsFloats = true | |
formatter.minimumIntegerDigits = 1 | |
formatter.minimumFractionDigits = 0 | |
formatter.maximumFractionDigits = 1 | |
let value = Double(self) / abbreviation.divisor | |
return formatter.string(from: NSNumber(value: value))! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Output