-
-
Save AliaksandrHabrusevich/33f137ae727ea445e05a5431d0d86843 to your computer and use it in GitHub Desktop.
iOS solution to convert large numbers to smaller format. See : http://stackoverflow.com/a/35504720/1661338
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
| extension Int { | |
| func formatUsingAbbrevation () -> String { | |
| let numFormatter = NSNumberFormatter() | |
| 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")] | |
| // you can add more ! | |
| 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 value = Double(self) / abbreviation.divisor | |
| numFormatter.positiveSuffix = abbreviation.suffix | |
| numFormatter.negativeSuffix = abbreviation.suffix | |
| numFormatter.allowsFloats = true | |
| numFormatter.minimumIntegerDigits = 1 | |
| numFormatter.minimumFractionDigits = 0 | |
| numFormatter.maximumFractionDigits = 1 | |
| return numFormatter.stringFromNumber(NSNumber (double:value))! | |
| } | |
| } | |
| let testValue:[Int] = [598, -999, 1000, -1284, 9940, 9980, 39900, 99880, 399880, 999898, 999999, 1456384, 12383474] | |
| testValue.forEach() { | |
| print ("Value : \($0) -> \($0.formatUsingAbbrevation ())") | |
| } | |
| ///// | |
| // Result : | |
| // Value : 598 -> 598 | |
| // Value : -999 -> -999 | |
| // Value : 1000 -> 1K | |
| // Value : -1284 -> -1.3K | |
| // Value : 9940 -> 9.9K | |
| // Value : 9980 -> 10K | |
| // Value : 39900 -> 39.9K | |
| // Value : 99880 -> 99.9K | |
| // Value : 399880 -> 0.4M | |
| // Value : 999898 -> 1M | |
| // Value : 999999 -> 1M | |
| // Value : 1456384 -> 1.5M | |
| // Value : 12383474 -> 12.4M | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment