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.
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:
Starting 0 works too:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With