Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Forked from gbitaudeau/Int+Extenstion.swift
Last active May 2, 2020 12:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertAudi/e2e11f2f7c8aacc46c05932e6897e698 to your computer and use it in GitHub Desktop.
Save RobertAudi/e2e11f2f7c8aacc46c05932e6897e698 to your computer and use it in GitHub Desktop.
Convert large numbers to smaller format
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))!
}
}
@RobertAudi
Copy link
Author

Example

let testValues: [Int] = [
  598,
  -999,
  1_000,
  -1_284,
  9_940,
  9_980,
  39_900,
  99_880,
  399_880,
  999_898,
  999_999,
  1_456_384,
  12_383_474
]

testValues.forEach() {
  print("Value : \($0) -> \($0.abbreviate())")
}

Output

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