I\'m trying to write a function to present thousands and millions into K\'s and M\'s For instance:
1000 = 1k
1100 = 1.1k
15000 = 15k
115000 = 115k
1000000 =
Here is my approach to it.
extension Int {
func shorted() -> String {
if self >= 1000 && self < 10000 {
return String(format: "%.1fK", Double(self/100)/10).replacingOccurrences(of: ".0", with: "")
}
if self >= 10000 && self < 1000000 {
return "\(self/1000)k"
}
if self >= 1000000 && self < 10000000 {
return String(format: "%.1fM", Double(self/100000)/10).replacingOccurrences(of: ".0", with: "")
}
if self >= 10000000 {
return "\(self/1000000)M"
}
return String(self)
}
Below are some examples:
print(913.shorted())
print(1001.shorted())
print(1699.shorted())
print(8900.shorted())
print(10500.shorted())
print(17500.shorted())
print(863500.shorted())
print(1200000.shorted())
print(3010000.shorted())
print(11800000.shorted())
913
1K
1.6K
8.9K
10k
17k
863k
1.2M
3M
11M