Comma Automatically Being Added to Textfield in Swift

Comma Automatically Being Added to TextField in Swift

In your storyboard select the artSizeTextField and remove its formatter.
Sample Image

Swift: Add comma and $ in the textfield when typing

First, you got some bad advice. You should not be using shouldChangeCharactersInRange to change the characters in a text field. That's for checking if the characters typed are valid for the field. The only thing you should do in this method is return true if the user entered digits or delete, otherwise false. (Remember, the user may be using an external keyboard so just having the keypad up isn't good enough to stop non-digit entry.)

Instead you should be using an @IBAction connected to the field's EditingChanged event. Inside this method is where you should update the text.

@IBAction func editingChanged(sender: UITextField) {
let digits = sender.text?.digitsOnly ?? "0"
sender.text = "$\(digits).00" // If I understand what you want.

The below extension should be somewhere in your code base. It's generally useful so store it in a gist or something, you will likely need it in future projects.

extension String {
var digitsOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")

You have to make sure that the IBAction is attached to the EditingChanged event:

Sample Image

For Swift 4x

extension String {
var digitsOnly: String {
return components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")

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

Instead of inserting the commas on your own in shouldChangeCharactersInRange:, you can use an NSNumberFormatterDecimalStyle 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 your shouldChangeCharactersInRange: delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if (([string isEqualToString:@"0"] || [string isEqualToString:@""]) && [textField.text rangeOfString:@"."].location < range.location) {
return YES;

// First check whether the replacement string's numeric...
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
bool isNumeric = [string isEqualToString:filtered];

// Then if the replacement string's numeric, or if it's
// a backspace, or if it's a decimal point and the text
// field doesn't already contain a decimal point,
// reformat the new complete number using
// NSNumberFormatterDecimalStyle
if (isNumeric ||
[string isEqualToString:@""] ||
([string isEqualToString:@"."] &&
[textField.text rangeOfString:@"."].location == NSNotFound)) {

// Create the decimal style formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:10];

// Combine the new text with the old; then remove any
// commas from the textField before formatting
NSString *combinedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *numberWithoutCommas = [combinedText stringByReplacingOccurrencesOfString:@"," withString:@""];
NSNumber *number = [formatter numberFromString:numberWithoutCommas];

NSString *formattedString = [formatter stringFromNumber:number];

// If the last entry was a decimal or a zero after a decimal,
// re-add it here because the formatter will naturally remove
// it.
if ([string isEqualToString:@"."] &&
range.location == textField.text.length) {
formattedString = [formattedString stringByAppendingString:@"."];

textField.text = formattedString;


// Return no, because either the replacement string is not
// valid or it is and the textfield has already been updated
// accordingly
return NO;

adding comma separator for numbers,every third digit while typing

You forgot the method name addTarget. Instead of

self.mainTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)


self.mainTextField.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

UITextField's numerical pad: dot instead of comma for float values

Potential duplicate of the SO Answer, use NSNumberFormatter

Example Swift:

let number = NSNumberFormatter().numberFromString(numberString)
if let number = number {
let floatValue = Float(number)

Example (Objective-C):

NSNumber *number = [[NSNumberFormatter new] numberFromString: numberString];
float floatValue = number.floatValue;

how to add a string after each comma in UITextfield

You can make it easier checking the text after editing changed control event and clean your string when the user types a space after each word. You can subclass your UITextField and it should look something like this:

class TagsField: UITextField, UITextFieldDelegate {
override func didMoveToSuperview() {
delegate = self
keyboardType = .alphabet
autocapitalizationType = .none
autocorrectionType = .no
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if text!.hasSuffix(", #") { text!.removeLast(3) } // clean the residue on end
return false
func prepareString() {
text = text!.components(separatedBy: CharacterSet.letters.inverted) // filtering non letters and grouping words
.filter{!$0.isEmpty} // filtering empty components
.map{ "#" + $0 + ", " } // add prefix and sufix to each word and append # to the end of the string
.string + "#"

override func deleteBackward() {
let _ = text!.popLast() // manually pops the last character when deliting
@objc func editingChanged(_ textField: UITextField) {
if text!.last == " " {
} else if !text!.hasPrefix("#") { // check if the first word being typed has the # prefix and add it if needed.
text!.insert("#", at: text!.startIndex)

extension Collection where Element: StringProtocol {
var string: String {
return String(joined())

Replace comma with decimal separator from TextField

When you click on button write below code for replace your string

let strReplace = txtField.text.replacingOccurrences(of: ",", with: ".", options: .literal, range: nil)// change "txtField" your textfield's object

Two blank space in UITextView automatically inserts a . (fullstop) after text in iPhone

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
//Check for double space
return !(range.location > 0 &&
[text length] > 0 &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[text characterAtIndex:0]] &&
[[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textView text] characterAtIndex:range.location - 1]]);


Above code will limit user to enter more than one blank space.

Related Topics

Leave a reply