【问题标题】:Convert high numbers to lower format [duplicate]将高数字转换为低格式[重复]
【发布时间】:2016-03-07 21:09:48
【问题描述】:

如何将高数字更改为:

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))"

【问题讨论】:

  • 看看 NSByteCountFormatter ...

标签: ios swift


【解决方案1】:
let formatter = NSByteCountFormatter()

就是这样;)

例子:

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

【讨论】:

    【解决方案2】:

    您可以将此功能添加为 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
    

    【讨论】:

    • 如何在这样的函数中使用它:textCell?.ll1.text = "\(String(thumbEmoji[indexPath.row].count))"?
    • textCell?.ll1.text = thumbEmoji[indexPath.row].count.shortLiteralDescription()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2018-09-21
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多