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.
Format the number with grouping attributes as shown here.
Output for the above code is
Here is a solution in swift 4.
Don't forget to add editingChanged action as below:
For Swift 4.0 Version of Lyndsey Scott's answer:
Instead of inserting the commas on your own in
shouldChangeCharactersInRange:
, you can use anNSNumberFormatterDecimalStyle
to handle the comma formatting for you. Even though it's called "decimal" style, it also inserts commas to appropriately group numbers into their thousands digits.Note: To simplify matters, I'll assume you only want the text field to accept numeric entries and I'll also add logic to limit the user's input to numbers.
Edit: I've updated the code to handle decimals also as per the OP's request.
To utilize
NSNumberFormatterDecimalStyle
's formatting upon every character entry, try adding this to yourshouldChangeCharactersInRange:
delegate method:Here is a version in Swift 4. I used it for integers, I didn't check with decimal numbers.
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:
Use the UITextFieldDelegate method: (your view controller needs to be a delegate of the textfield)
When a character is added to the textField, it will call this method. You can then insert commas wherever you want.
Note: people can paste text into textfields, delete values, move the cursor, etc. so you have a lot of tests to consider.
There are lots of similar questions on SO, e.g. How to put comma and decimals in my UITextField dynamically?
Auto suggest in UITextfield with comma separation
etc