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 =
For swift 4.0. its work completely fine and answer based on @user3483203
Function for convert Double value to String
func formatPoints(num: Double) ->String{
var thousandNum = num/1000
var millionNum = num/1000000
if num >= 1000 && num < 1000000{
if(floor(thousandNum) == thousandNum){
return("\(Int(thousandNum))k")
}
return("\(thousandNum.roundToPlaces(places: 1))k")
}
if num > 1000000{
if(floor(millionNum) == millionNum){
return("\(Int(thousandNum))k")
}
return ("\(millionNum.roundToPlaces(places: 1))M")
}
else{
if(floor(num) == num){
return ("\(Int(num))")
}
return ("\(num)")
}
}
Make one Double extension
extension Double {
/// Rounds the double to decimal places value
mutating func roundToPlaces(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return Darwin.round(self * divisor) / divisor
}
}
Usage of above function
UILABEL.text = formatPoints(num: Double(310940)!)
Output :