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

后端 未结 13 2095
陌清茗
陌清茗 2021-01-01 12:51

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 =          


        
13条回答
  •  隐瞒了意图╮
    2021-01-01 13:18

    Solution above (from @qlear) in Swift 3:

    func formatPoints(num: Double) -> String {
        var thousandNum = num / 1_000
        var millionNum = num / 1_000_000
        if  num >= 1_000 && num < 1_000_000 {
            if  floor(thousandNum) == thousandNum {
                return("\(Int(thousandNum))k")
            }
            return("\(thousandNum.roundToPlaces(1))k")
        }
        if  num > 1_000_000 {
            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
        mutating func roundToPlaces(_ places : Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self.rounded() * divisor) / divisor
        }
    }
    

提交回复
热议问题