Adding Thousand Separator to Int in Swift

Adding Thousand Separator to Int in Swift

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

update: 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"

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    // "$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"

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

How to add thousand separator in type Int and Float?

Number formatters do not start with a "number string"; they start with a number. Thus, for example, using the Formatter extension code you already have:

let n = 5000
let s = Formatter.withSeparator.string(for: n)
// s is now "5,000"

But let's say what you start with really is a string. Then you could say, for example:

let str = "5000"
let s = Formatter.withSeparator.string(for: Float(str)!)
// s is now "5,000"

Observe that the decimal information is lost in this process. If that were important to you, you'd need to add that requirement to the formatter itself. You are making a string, and you have to provide all information about how you want that string to look. For example:

let str = "5000.00"
let f = Formatter.withSeparator
f.minimumFractionDigits = 2
let s = f.string(for: Float(str)!)
// s is now "5,000.00"

If you omit the mimimumFractionDigits info, you would get "5,000" again; the original appearance of the string we started with is completely unimportant.

Adding Thousand Separator Automatically (Swift)

It is better to accumulate your value in a separate string that doesn't have the formatting applied rather than using the text field as your data model. You can then format the decimal and display it in the label as required using a NumberFormatter:

let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()

var currentInput: String = "0" {
didSet {
self.displayResultLabel?.text = self.currentDisplay
}

var currentValue: Double {
return Double(self.currentInput) ?? 0
}

var currentDisplay: String {
return formatter.string(from: NSNumber(value:self.currentValue)) ?? "0"
}

func addDigit(_ digit: Int) {
if currentInput.count < 14 {
let newValue = self.currentValue * 10 + Double(digit)
self.currentInput = "\(newValue)"
}
}

@IBAction func numberPressed(_ sender: UIButton) {
guard let digit = Int(sender.currentTitle!) else {
return
}

self.addDigit(digit)
}

Format a number to string with thousand separators and always has 2 digits after decimal point in swift

See NSNumberFormatter.minimumFractionDigits.

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.minimumFractionDigits = 2
let s2 = formatter.stringFromNumber(n) //5,432.10

Swift how to format a large number with thousands separators?

Swift Xcode 6.3, SOLVED (I decided to leave the $ in the code). If you don't want a $ in the output, change .CurrencyStyle to .DecimalStyle

var fv = 3534234.55 
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0;
resultFV.text = formatter.stringFromNumber(fv) // result: $3,534,235 –

Format double number without thousand separator?

You need to use the NSNumberFormatter on the number and explicitly set the grouping separator to empty string:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US") // locale determines the decimal point (. or ,); English locale has "."
formatter.groupingSeparator = "" // you will never get thousands separator as output
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.numberStyle = .DecimalStyle
let result = formatter.stringFromNumber(1233.99) // you will always get string 1233.99


Related Topics



Leave a reply



Submit