ios 在 Swift 中为 Int 添加千位分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29999024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:51:44  来源:igfitidea点击:

Adding Thousand Separator to Int in Swift

iosswiftseparator

提问by alionthego

I am fairly new to Swift and having a great deal of trouble finding a way to add a space as a thousand separator.

我对 Swift 相当陌生,在找到一种将空格添加为千位分隔符的方法时遇到了很多麻烦。

What I am hoping to achieve is taking the result of a calculation and displaying it in a textfield so that the format is:

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

2 358 000

2 358 000

instead of

代替

2358000

2358000

for example.

例如。

I am not sure if I should be formatting the Int value and then converting it to a String, or adding the space after the Int value is converted to a String. Any help would be greatly appreciated.

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

回答by Leo Dabus

You can use NSNumberFormatter to specify a different grouping separator as follow:

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

update: Xcode 11.5 ? Swift 5.2

更新:Xcode 11.5?斯威夫特 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"


If you need to display your value as currency with current locale or with a fixed locale:

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

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) }
}


Usage:

用法:

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"

Note: If you would like to have a space with the same width of a period you can use "\u{2008}"

注意:如果您想要一个与句点宽度相同的空格,您可以使用 "\u{2008}"

unicode spaces

Unicode 空格

formatter.groupingSeparator = "\u{2008}"

回答by Airspeed Velocity

You want to use NSNumberFormatter:

你想使用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"

回答by Imanou Petit

With Swift 5, when you need to format the display of numbers, NumberFormatteris the right tool.

使用 Swift 5,当您需要格式化数字的显示时,NumberFormatter它是正确的工具。



NumberFormatterhas a property called numberStyle. numberStylecan be set to a value of NumberFormatter.Style.decimalin order to set the formatter's style to decimal.

NumberFormatter有一个名为numberStyle. numberStyle可以设置为一个值,NumberFormatter.Style.decimal以便将格式化程序的样式设置为十进制。

Therefore, in the simplest case when you want to format a number with decimal style, you can use the following Playground code:

因此,在最简单的情况下,当您想使用十进制样式格式化数字时,可以使用以下 Playground 代码:

import Foundation

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

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

According to the user's current locale, this code will print Optional("2,358,000")for en_USor Optional("2?358?000")for fr_FR.

根据用户的当前区域,这段代码将打印Optional("2,358,000")EN_USOptional("2?358?000")fr_FR时



Note that the following code snippet that uses the NumberFormatter's localeproperty set to Locale.currentis equivalent to the previous Playground code:

请注意,以下使用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))


The Playground code below that uses the NumberFormatter's groupingSeparatorproperty set to Locale.current.groupingSeparatoris also equivalent to the former:

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

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))


Otherwise, if you want to set the number formatting with a specific locale formatting style, you may use the following Playground code:

否则,如果您想使用特定的语言环境格式设置数字格式,您可以使用以下 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")


However, if what you really want is to enforce a specific grouping separator, you may use the Playground code below:

但是,如果您真正想要的是强制执行特定的分组分隔符,您可以使用下面的 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")

回答by David Seek

Leo Dabus's answer translated to Swift 3:

Leo Dabus 的回答转化为Swift 3

Into any .swiftfile, out of a class:

进入任何.swift文件,退出一个类:

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)) ?? ""
    }
}

Usage:

用法:

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

回答by Bréndal Teixeira

I was looking for a currency format like $100,000.00 I accomplished it customizing the implementation Leo Dabus like this

我正在寻找一种像 $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) ?? ""
    }
}

回答by Khalid Moin

Code:

代码:

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

Output:

输出:

5 000 000

5 000 000

回答by Василий Синишин

Try this

尝试这个

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)
}

The call:

电话:

addPoints(inputNumber: "123456")

The result:

结果:

123 456 (or 123,456)

123 456 (或 123,456)