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

后端 未结 13 2100
陌清茗
陌清茗 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

    Minor improvement to @chrisz answer, Swift-4 Doble extension - This works fine in all cases.

    extension Double {
    
      // Formatting double value to k and M
      // 1000 = 1k
      // 1100 = 1.1k
      // 15000 = 15k
      // 115000 = 115k
      // 1000000 = 1m
      func formatPoints() -> String{
            let thousandNum = self/1000
            let millionNum = self/1000000
            if self >= 1000 && self < 1000000{
                if(floor(thousandNum) == thousandNum){
                    return ("\(Int(thousandNum))k").replacingOccurrences(of: ".0", with: "")
                }
                return("\(thousandNum.roundTo(places: 1))k").replacingOccurrences(of: ".0", with: "")
            }
            if self > 1000000{
                if(floor(millionNum) == millionNum){
                    return("\(Int(thousandNum))k").replacingOccurrences(of: ".0", with: "")
                }
                return ("\(millionNum.roundTo(places: 1))M").replacingOccurrences(of: ".0", with: "")
            }
            else{
                if(floor(self) == self){
                    return ("\(Int(self))")
                }
                return ("\(self)")
            }
        }
    
        /// Returns rounded value for passed places
        ///
        /// - parameter places: Pass number of digit for rounded value off after decimal
        ///
        /// - returns: Returns rounded value with passed places
        func roundTo(places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
    }
    




提交回复
热议问题