How to add a thousand separator in String for SWIFT

I’m pretty new to SWIFT and need your help. I need a function that takes String and Separator and returns String. Input has only numbers, still in String. Basically it should look like this:

func formatNumber(input: String, separator: String) -> String

The problem is it should be done with NO extensions. Only native SWIFT – String elements.

What I’ve done for now is:

func formatNumber(input: String, separator: String) -> String {         var newText = ""         for (index , character) in input.enumerated() {             if index != 0 && index % 3 == 0 {                 newText.append(separator)             }             newText.append(character)         }         return newText     } 

But it puts separator from the front, not from the back. I do not need a code, just explain the logic it should be done! Thank you!

Asked on August 31, 2020 in Swift.
Add Comment
2 Answer(s)
import UIKit let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.groupingSeparator = ","  print(formatter.string(from: 1234)!) 
Answered on August 31, 2020.
Add Comment

If you work from the front, you need to not look at the index, but the index if you count from the back of the string.

Figure out how to convert the index which goes from 0 to count-1 to count from count-1 to zero. Use that to figure out where the commas go.

BTW, what are the requirements? Will you be passed numbers with a decimal portion? (e.g. 123.456)? And if so, should you handle different decimal separators (in Germany, for example, the decimal separator is a comma, not a period.)

Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.