您可以使用NSNumberFormatter指定其他分组分隔符,如下所示:
更新: Xpre 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 = 2358000let intFormatted = int.formattedWithSeparator // "2 358 000"let decimal: Decimal = 2358000let decimalFormatted = decimal.formattedWithSeparator // "2 358 000"let decimalWithFractionalDigits: Decimal = 2358000.99let 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 // "$1,234.99"1234.99.currencyUS // "$1,234.99"1234.99.currencyFR // "1 234,99 €"1234.99.currencyBR // "R$ 1.234,99"1234.99.calculator // "1 234.99"
注意:如果您希望空格的宽度等于句点的宽度,则可以使用
"u{2008}"Unipre空间
formatter.groupingSeparator = "u{2008}"


