If you need to limit user input on a UITextField to decimal characters only, either for currency or something else here’s a bit of code that accomplishes that. There’s lots of ways to do this even with the use of NSNumberFormatter and/or NSScanner.
First of all you need set the UITextFieldDelegate on your View Controller and then set the View as the delegate for your UITextField. You do this by changing a line in your View Controller’s .h file to:
@interface MyViewController : UIViewController |
and then either set the UITextField’s delegate in your View Controller’s .m file in the viewWillAppear method for example like:
myTextField.delegate = self;
|
or in Interface Builder by selecting the UITextField and in the Connections Inspector drag from the “delegate” to your View Controller.
Then you can implement the following delegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet]; // allow backspace if (range.length > 0 && [string length] == 0) { return YES; } // do not allow . at the beggining if (range.location == 0 && [string isEqualToString:@"."]) { return NO; } // set the text field value manually NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string]; newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""]; textField.text = newValue; // return NO because we're manually setting the value return NO; } |
As you can see from the code’s comments we allow the user to delete characters, check if the separator is not at the start and removing any non decimal characters that user types or pastes.
You might also want to set your UITextField to use a decimal keyboard by doing this:
myTextField.keyboardType = UIKeyboardTypeDecimalPad;
|
Beware it only works on the iPhone (iPad doesn’t have this keyboard and it will default to the normal one) and only on iOS 4.1 or greater.
Hope this helps, happy coding!


Hello, thanks for this informative blog, I had stuck in this problem, and your blog helped me to sort this problem, I have to do fewer more checks here and I am getting confused on how to do it.
I want the numbers to be entered in this format
for ex: 89.9 or 999.9 i.e after entering three digits he can enter a dot and then only 4th digit and not 5th digit i.e after decimal point only 1 digit
llly after entering 2 digits he can enter a dot and then only 3rd digit i.e after decimal point only 1 digit
Can you please help me out
I tried this way,
if(range.location == 3 && ![string isEqualToString:@"."] )
{
return NO;
}
it solves only one problem but not the second one .So please help me out