在 Swift 中向 Int 添加千位分隔符

Adding Thousand Separator to Int in Swift

我是 Swift 的新手,在寻找添加 space 作为千位分隔符的方法时遇到了很多麻烦。

我希望实现的是获取计算结果并将其显示在文本字段中,以便格式为:

2 358 000

而不是

2358000

例如。

我不确定是否应该格式化 Int 值然后将其转换为字符串,或者在 Int 值转换为字符串后添加 space。任何帮助将不胜感激。

您可以使用 NSNumberFormatter 指定不同的分组分隔符,如下所示:

更新:Xcode 11.5 • Swift 5.2

extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.groupingSeparator = " "
        return formatter
    }()
}

extension Numeric {
    var formattedWithSeparator: String { Formatter.withSeparator.string(for: self) ?? "" }
}

2358000.formattedWithSeparator  // "2 358 000"
2358000.99.formattedWithSeparator  // "2 358 000.99"

let int = 2358000
let intFormatted = int.formattedWithSeparator  // "2 358 000"

let decimal: Decimal = 2358000
let decimalFormatted = decimal.formattedWithSeparator  // "2 358 000"

let decimalWithFractionalDigits: Decimal = 2358000.99
let decimalWithFractionalDigitsFormatted = decimalWithFractionalDigits.formattedWithSeparator // "2 358 000.99"

如果您需要在当前语言环境或固定语言环境中将您的价值显示为货币:

extension Formatter {
    static let number = NumberFormatter()
}
extension Locale {
    static let englishUS: Locale = .init(identifier: "en_US")
    static let frenchFR: Locale = .init(identifier: "fr_FR")
    static let portugueseBR: Locale = .init(identifier: "pt_BR")
    // ... and so on
}
extension Numeric {
    func formatted(with groupingSeparator: String? = nil, style: NumberFormatter.Style, locale: Locale = .current) -> String {
        Formatter.number.locale = locale
        Formatter.number.numberStyle = style
        if let groupingSeparator = groupingSeparator {
            Formatter.number.groupingSeparator = groupingSeparator
        }
        return Formatter.number.string(for: self) ?? ""
    }
    // Localized
    var currency:   String { formatted(style: .currency) }
    // Fixed locales
    var currencyUS: String { formatted(style: .currency, locale: .englishUS) }
    var currencyFR: String { formatted(style: .currency, locale: .frenchFR) }
    var currencyBR: String { formatted(style: .currency, locale: .portugueseBR) }
    // ... and so on
    var calculator: String { formatted(groupingSeparator: " ", style: .decimal) }
}

用法:

1234.99.currency    // ",234.99"

1234.99.currencyUS  // ",234.99"
1234.99.currencyFR  // "1 234,99 €"
1234.99.currencyBR  // "R$ 1.234,99"

1234.99.calculator  // "1 234.99"

注意:如果您希望 space 具有相同的句点宽度,您可以使用 "\u{2008}"

unicode spaces

formatter.groupingSeparator = "\u{2008}"

您想使用 NSNumberFormatter:

let fmt = NSNumberFormatter()
fmt.numberStyle = .DecimalStyle
fmt.stringFromNumber(2358000)  // with my locale, "2,358,000"
fmt.locale = NSLocale(localeIdentifier: "fr_FR")
fmt.stringFromNumber(2358000)  // "2 358 000"

Leo Dabus 的回答翻译成 Swift 3

进入任何 .swift 文件,出 class:

struct Number {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.groupingSeparator = " " // or possibly "." / ","
        formatter.numberStyle = .decimal
        return formatter
    }()
}
extension Integer {
    var stringWithSepator: String {
        return Number.withSeparator.string(from: NSNumber(value: hashValue)) ?? ""
    }
}

用法:

let myInteger = 2358000
let myString = myInteger.stringWithSeparator  // "2 358 000"

配合Swift 5、当你需要格式化数字的显示时,NumberFormatter是合适的工具。


NumberFormatter 有一个 属性 叫做 numberStylenumberStyle 可以设置为 NumberFormatter.Style.decimal 的值,以便将格式化程序的样式设置为十进制。

因此,在最简单的情况下,当你想用小数格式格式化一个数字时,你可以使用下面的 Playground 代码:

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal

let amount = 2358000
let formattedString = formatter.string(for: amount)
print(String(describing: formattedString))

根据用户当前的语言环境,此代码将打印 Optional("2,358,000") for en_USOptional("2 358 000") for fr_FR.


请注意,以下使用 NumberFormatterlocale 属性 设置为 Locale.current 的代码片段等同于之前的 Playground 代码:

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale.current

let amount = 2358000
let formattedString = formatter.string(for: amount)
print(String(describing: formattedString))

下面使用 NumberFormattergroupingSeparator 属性 设置为 Locale.current.groupingSeparator 的 Playground 代码也等同于前者:

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = Locale.current.groupingSeparator

let amount = 2358000
let formattedString = formatter.string(for: amount)
print(String(describing: formattedString))

否则,如果您想使用特定区域设置格式样式设置数字格式,您可以使用以下 Playground 代码:

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "fr_FR")

let amount = 2358000
let formattedString = formatter.string(for: amount)
print(String(describing: formattedString))
// prints: Optional("2 358 000")

但是,如果您真正想要的是强制执行特定的分组分隔符,您可以使用下面的 Playground 代码:

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "

let amount = 2358000
let formattedString = formatter.string(for: amount)
print(String(describing: formattedString))
// prints: Optional("2 358 000")

试试这个

func addPoints(inputNumber: NSMutableString){
    var count: Int = inputNumber.length
    while count >= 4 {
        count = count - 3
        inputNumber.insert(" ", at: count) // you also can use "," 
    }
    print(inputNumber)
}

来电:

addPoints(inputNumber: "123456")

结果:

123 456 (or 123,456)

我正在寻找像 $100,000.00 这样的货币格式 我像这样自定义实施 Leo Dabus

extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencyGroupingSeparator = ","
        formatter.locale = Locale(identifier: "en_US") //for USA's currency patter
        return formatter
    }()
}

extension Numeric {
    var formattedWithSeparator: String {
        return Formatter.withSeparator.string(for: self) ?? ""
    }
}

代码:

//5000000
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.locale = Locale(identifier: "en_US")
formatter.numberStyle = .decimal. 

输出:

5 000 000