Mackey18 Mackey18 - 1 year ago 76
iOS Question

Good way for user to input NSNumbers into a variable

I'm making an app for my football club to make little bets with each other. I'm trying to find a way of receiving a price input from a user. I need the number to be in a form of

where it doesn't matter how many X's go before the decimal point. I've thought about a couple of options but I'm just not experienced enough to decide which is the best.

What I've thought about so far:

  1. Create a text field which shows the number keypad. Then I can use
    [numberFormatter numberFromString: text];
    . However this seems a bit too risky. For instance, if the user were to type in
    or something similar, then the app would accept those values, causing problems later on along the line.

  2. The other idea I had was to use some sort of picker, but then we'll be limited to a fixed set of values.

What do you recommend? I'd probably use the text field with some sort of check for the correct format input, but I'm not entirely sure how I'd go about doing that.

EDIT: Just checked the eBay app, and they have a really nice way of doing it. They use a text field that limits to two digits after the decimal point. How on earth would I program that?

Answer Source

To build on @SteveC's correct answer, some additional checks are required to limit not only the number of digits after the decimal point; but the number of decimal points (as you mentioned in the original question.):

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    if ([string length] == 0)
        return YES;
    NSInteger firstDecimalLocation = [[textField text] rangeOfString:@"."].location;
    if( firstDecimalLocation != NSNotFound ) {
        if( [string isEqualToString:@"."] ) {
            return NO;
        if( firstDecimalLocation == range.location - 3 ) {
            return NO;
    NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString:@"."];

    NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
    [_alnum formUnionWithCharacterSet:numberSet];
    NSCharacterSet *nonNumberSet = [_alnum invertedSet];

    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);

Note that this presumes you are using a UIKeyboardTypeNumbersAndPunctuation, rather than test for it in the UITextFieldDelegate method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download