When entering numbers into a string, display it as a calculator output. The type of output is excluded, 934,432. How else can you implement this task by eliminating the output using the built-in NSFormatter method and the like? Thank.

let newNumbers = makeNumber(number: "1234567894") print(newNumbers) } func makeNumber(number: String) -> String { let reversed = String(number.reversed()) var newText = "" for (index, character) in reversed.enumerated() { if index != 0 && index % 3 == 0 { newText.append(",") } newText.append(String(character)) } return String(newText.reversed()) 

When entering the digits number: "1234567894" at the output we get 1,234,567,894 . Excluded at the output ,234,567,894 if entered 234567894 . Insert commas from back to before separating by 3 characters, as it is displayed in the calculator.

  • one
    Explain in more detail, it is not entirely clear what you want. - VAndrJ
  • one
    When entering the digits number: "1234567894" at the output we get 1,234,567,894. Excluded at the output, 234,567,894 if 234567894 is entered. Insert commas from back to before separating 3 characters each, as it appears in the calculator. - Evgeniy

2 answers 2

NSNumberFormatter is of course the best. But if you want to hand it over.
With the line there will be a lot of code and not quite beautiful. You can do with the number:

 let number = 12345678 print(getNumberComponents(number).joined(separator: "'")) func getNumberComponents(_ number: Int, arr: [String] = []) -> [String] { guard number != 0 else { return arr } return getNumberComponents(number / 1000, arr: ([String(number % 1000)] + arr)) } // MARK: - Strings func getStridesArray(from text: String) -> [String] { var result: [String] = [] let characters = Array(text) stride(from: characters.count, through: 0, by: -3).forEach { result.append(String(characters[max($0-3, 0)..<$0])) } return result.reversed() } print(getStridesArray(from: "12345678").joined(separator: "'")) 
     re.sub(r"(.)(?=(...)+$)", "\\1,", x) 

    Complete code: https://ideone.com/MnX4LE

     import re try: while True: x = input() print(re.sub(r"(.)(?=(...)+$)", "\\1,", x)) except (EOFError): pass