iOS Swift 4 Coding

How to show thousand separators in Swift 4?

5 views August 25, 2018 August 26, 2018 bicobro 0

The best way to add thousand separators with Swift 4 is to use the NumberFormatter class. The following properties are relevant for thousand separators:

  • usesGroupingSeparator – Define whether or not you want to show the thousand separator.
  • groupingSeparator – Define what the separator will look like. Normally for United States you use “,” as the separator.
  • groupingSize – The number of digits between each separator. Normally this will be “3”.
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal          // Set defaults to the formatter that are common for showing decimal numbers
numberFormatter.usesGroupingSeparator = true    // Enabled separator
numberFormatter.groupingSeparator = ","         // Set the separator to "," (e.g. 1000000 = 1,000,000)
numberFormatter.groupingSize = 3                // Set the digits between each separator

let myDouble = 1234567.89
let myFormattedDouble = numberFormatter.string(for: myDouble)

# myFormattedDouble = 1,234,567.89

 

Was this helpful?