Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dynamically format a number to have commas in a UITextField entry?

I want to have commas dynamically added to my numeric UITextField entry while the user is typing.

For example: 123,456 and 12,345,678, but not like this 123,45 or 123,4567.

How does one automatically append the commas while a user is typing a number in Objective-C?

Edit: I'd also like to be able to allow the user to input decimals.

like image 394
Windy_Cheng Avatar asked Dec 05 '14 04:12

Windy_Cheng


1 Answers

Here is a version in Swift 4. I used it for integers, I didn't check with decimal numbers.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

     // Uses the number format corresponding to your Locale
     let formatter = NumberFormatter()
     formatter.numberStyle = .decimal
     formatter.locale = Locale.current
     formatter.maximumFractionDigits = 0


    // Uses the grouping separator corresponding to your Locale
    // e.g. "," in the US, a space in France, and so on
    if let groupingSeparator = formatter.groupingSeparator {

        if string == groupingSeparator {
            return true
        }


        if let textWithoutGroupingSeparator = textField.text?.replacingOccurrences(of: groupingSeparator, with: "") {
            var totalTextWithoutGroupingSeparators = textWithoutGroupingSeparator + string
            if string.isEmpty { // pressed Backspace key
                totalTextWithoutGroupingSeparators.removeLast()
            }
            if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators),
                let formattedText = formatter.string(from: numberWithoutGroupingSeparator) {

                textField.text = formattedText
                return false
            }
        }
    }
    return true
}

The big advantage of this method is that it uses the grouping separator defined in your current locale (region), because not everybody uses the comma as a grouping separator.

Works with 0, backspace, but, again, I didn't test it with decimals. You are free to enhance this code if you worked it out with decimals.

Examples:

  • Enter : "2" -> "2"
  • Enter : "3" -> "23"
  • Enter : "6" -> "236"
  • Enter : "7" -> "2,367"
  • Enter : "0" 3 times -> "2,367,000"
  • Backspace -> "236,700"

Starting 0 works too:

  • Enter : "0" -> "0"
  • Enter : "2" -> "2"
like image 105
Frédéric Adda Avatar answered Oct 23 '22 23:10

Frédéric Adda