Adding Thousand Separator to Int in Swift

不问归期 提交于 2019-11-26 08:22:02

问题


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

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

instead of

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.


回答1:


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

update: Xcode 9 • Swift 4

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

extension Numeric {
    var formattedWithSeparator: String {
        return 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"

Xcode 8.3.2 • Swift 3.1

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

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

unicode spaces

formatter.groupingSeparator = "\u{2008}"



回答2:


You want to use 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"



回答3:


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


NumberFormatter has a property called numberStyle. numberStyle can be set to a value of NumberFormatter.Style.decimal in order to set the formatter's style to decimal.

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

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_US or Optional("2 358 000") for fr_FR.


Note that the following code snippet that uses the NumberFormatter's locale property set to Locale.current is equivalent to the previous Playground code:

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 groupingSeparator property set to Locale.current.groupingSeparator is also equivalent to the former:

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:

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:

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



回答4:


Leo Dabus's answer translated to Swift 3:

Into any .swift file, out of a 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)) ?? ""
    }
}

Usage:

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



回答5:


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)



来源:https://stackoverflow.com/questions/29999024/adding-thousand-separator-to-int-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!