将高数字转换为低格式

时间:2016-03-07 21:09:49

标签: ios swift

如何将高数字更改为:

1,000 = 1K
1,250 = 1,2K
10,200 = 10,2K
102,000 = 102K
1,200,000 = 1,2M

或类似的东西?

这是我设置数字的方式:

textCell?.ll1.text = "\(String(thumb[indexPath.row].count))"
textCell?.ll2.text = "\(String(love[indexPath.row].count))"

2 个答案:

答案 0 :(得分:0)

let formatter = NSByteCountFormatter()

就是这样;)

示例:

let oneFormattedNumber = formatter.stringFromByteCount(1025000000000)
let formattedList = [1_000, 1_250, 10_200, 102_000, 1_200_000].map(formatter.stringFromByteCount)

答案 1 :(得分:0)

  

您可以将此功能添加为Int:

的扩展程序
extension Int {
  func shortLiteralDescription() -> String {
        var factor = 0
        let tokens = ["","K", "M", "G","T","P"] //If you think you will need to express more, add them here
        var value = Double(self);
        while (value > 1000) {
            value /= 1000
            factor++
        }
        return "\(value)\(tokens[factor])"
    }
}

然后:

400200.shortLiteralDescription()   //400.2K
4000.shortLiteralDescription()     //4.0K