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 =
The extension below does the following-
.0
decimals).Will format thousands upto 9999 in currency format i.e. with a comma like 9,999
extension Double {
var kmFormatted: String {
if self >= 10000, self <= 999999 {
return String(format: "%.1fK", locale: Locale.current,self/1000).replacingOccurrences(of: ".0", with: "")
}
if self > 999999 {
return String(format: "%.1fM", locale: Locale.current,self/1000000).replacingOccurrences(of: ".0", with: "")
}
return String(format: "%.0f", locale: Locale.current,self)
}
}
Usage:
let num: Double = 1000001.00 //this should be a Double since the extension is on Double
let millionStr = num.kmFormatted
print(millionStr)
Prints 1M
And here it is in action-