首页 > 解决方案 > 如何在swift 4中为每4位添加逗号或空格?

问题描述

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

例子: 18686305 1868,6305 or 1868 6305

我该怎么做 swift 4?

标签: iosswift

解决方案


ANumberFormatter旨在将数值转换为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"
}

和变量遵循Unicode 技术标准 #positiveFormat 35 。negativeFormat


推荐阅读