Search code examples
iosswiftnumbersswift2format

Swift 2.0 Format 1000's into a friendly K's


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?


Solution

  • func formatPoints(num: Double) ->String{
        let thousandNum = num/1000
        let millionNum = num/1000000
        if num >= 1000 && num < 1000000{
            if(floor(thousandNum) == thousandNum){
                return("\(Int(thousandNum))k")
            }
            return("\(thousandNum.roundToPlaces(1))k")
        }
        if num > 1000000{
            if(floor(millionNum) == millionNum){
                return("\(Int(thousandNum))k")
            }
            return ("\(millionNum.roundToPlaces(1))M")
        }
        else{
            if(floor(num) == num){
                return ("\(Int(num))")
            }
            return ("\(num)")
        }
    
    }
    
    extension Double {
        /// Rounds the double to decimal places value
        func roundToPlaces(places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return round(self * divisor) / divisor
        }
    }
    

    The updated code should now not return a .0 if the number is whole. Should now output 1k instead of 1.0k for example. I just checked essentially if double and its floor were the same.

    I found the double extension in this question: Rounding a double value to x number of decimal places in swift