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 = 1m
Here is where I got so far:
func formatPoints(num: Int) -> String {
let newNum = String(num / 1000)
var newNumString = "\(num)"
if num > 1000 && num < 1000000 {
newNumString = "\(newNum)k"
} else if num > 1000000 {
newNumString = "\(newNum)m"
}
return newNumString
}
formatPoints(51100) // THIS RETURNS 51K instead of 51.1K
How do I get this function to work, what am I missing?
extension Int {
var roundedWithAbbreviations: String {
let number = Double(self)
let thousand = number / 1000
let million = number / 1000000
if million >= 1.0 {
return "\(round(million*10)/10)M"
}
else if thousand >= 1.0 {
return "\(round(thousand*10)/10)k"
}
else {
return "\(self)"
}
}
}
print(11.roundedWithAbbreviations) // "11"
print(11111.roundedWithAbbreviations) // "11.1k"
print(11111111.roundedWithAbbreviations) // "11.1M"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With