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!