Here is the version in Swift 3. I used it for integers, I did not check 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 // eg "," 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 == "" { // pressed Backspace key totalTextWithoutGroupingSeparators.characters.removeLast() } if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators), let formattedText = formatter.string(from: numberWithoutGroupingSeparator) { textField.text = formattedText return false } } } return true }
The great advantage of this method is that it uses the grouping delimiter defined in your current locale (region), since not everyone uses a comma as the grouping delimiter.
Works with 0, backspace, but, again, I have not tested it with decimal places. You can improve this code if you developed it with decimal places.
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 also works:
- Enter: "0" โ "0"
- Enter: "2" โ "2"
source share