Skip to content

Instantly share code, notes, and snippets.

@gbitaudeau
Created March 3, 2017 09:44
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gbitaudeau/daa4d6dc46517b450965e9c7e13706a3 to your computer and use it in GitHub Desktop.
Save gbitaudeau/daa4d6dc46517b450965e9c7e13706a3 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
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
@TheJoker92
Copy link

I don't find the license for this extension, is a MIT one?

I appreciate this work anyway. Thank you :)

@hrool20
Copy link

hrool20 commented Aug 29, 2020

I think there is an error. If you try to format the number 1000, the output is not 1K. The solution for this is to change the abbreviation's array to:
Captura de Pantalla 2020-08-28 a la(s) 20 06 47

I hope I can help 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment