如何在Swift 4中为每4位数字添加逗号或空格?

时间:2018-07-31 23:10:08

标签: ios swift

我的情况有点特殊,我需要每4位插入空格或逗号。

示例: 18686305 1868,6305 or 1868 6305

如何快速完成4?

1 个答案:

答案 0 :(得分:3)

NumberFormatter设计为根据预定义格式将数值转换为String值。对于您而言,以下代码将每四位数插入分组分隔符:

import Foundation

let groupingSeparator = "," // determined based on user input, as per the question

let formatter = NumberFormatter()
formatter.positiveFormat = "####,####"
formatter.negativeFormat = "-####,####"
formatter.groupingSeparator = groupingSeparator

if let string = formatter.string(from: 18686305) {
    print(string) // prints "1868,6305"
}

positiveFormatnegativeFormat变量紧跟Unicode Technical Standard #35