我的情况有点特殊,我需要为每4位数字插入空格或逗号。
示例:18686305 1868,6305 or 1868 6305
在swift 4中我该怎么做?
发布于 2018-08-01 07:24:36
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"
}
positiveFormat
和negativeFormat
变量跟在Unicode Technical Standard #35后面。
https://stackoverflow.com/questions/51623312
复制相似问题