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

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

    To add to the answers, here's a Swift 4.X version of this using a loop to easily add/remove units if necessary:

    extension Double {
        var shortStringRepresentation: String {
            if self.isNaN {
                return "NaN"
            }
            if self.isInfinite {
                return "\(self < 0.0 ? "-" : "+")Infinity"
            }
            let units = ["", "k", "M"]
            var interval = self
            var i = 0
            while i < units.count - 1 {
                if abs(interval) < 1000.0 {
                    break
                }
                i += 1
                interval /= 1000.0
            }
            // + 2 to have one digit after the comma, + 1 to not have any.
            // Remove the * and the number of digits argument to display all the digits after the comma.
            return "\(String(format: "%0.*g", Int(log10(abs(interval))) + 2, interval))\(units[i])"
        }
    }
    

    Examples:

    $ [1.5, 15, 1000, 1470, 1000000, 1530000, 1791200000].map { $0.shortStringRepresentation }
    [String] = 7 values {
      [0] = "1.5"
      [1] = "15"
      [2] = "1k"
      [3] = "1.5k"
      [4] = "1M"
      [5] = "1.5M"
      [6] = "1791.2M"
    }
    

提交回复
热议问题