4

I need to restrict user to enter only two digit after decimal point. I have achieved this by following code in textfield delegate shouldChangeCharactersInRange. But its allowing to enter more than one dot. how to restrict this? Thanks in advance.

            NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSArray *sep = [newString componentsSeparatedByString:@"."];
            if([sep count]>=2)
            {
                NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
                NSLog(@"sepStr:%@",sepStr);

                return !([sepStr length]>2);
            }
            return YES;
2
  • 1
    please don't forget that different countries use different decimal separators. So just using . might not be enough.
    – Novarg
    Oct 16, 2012 at 9:22
  • @Gowtham: I just used your code and just put extra two lines.. It's working fine.. Ignore the NSLog.
    – Manu
    Oct 16, 2012 at 9:32

6 Answers 6

12

The best way is to use Regular Expression in shouldChangeCharactersInRange: delegate method like this

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

    NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSString *expression = @"^([0-9]*)(\\.([0-9]+)?)?$";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    NSUInteger noOfMatches = [regex numberOfMatchesInString:newStr
                                                        options:0
                                                          range:NSMakeRange(0, [newStr length])];
    if (noOfMatches==0){
        return NO;
    }
    return YES;
}

After implementing this valid strings are:
12.004546
4546.5456465
.5464
0.454

So on....

You can also restrict number of integer after decimal by using this Regular Expression

@"^([0-9]*)(\\.([0-9]{0,2})?)?$"

After implementing this valid strings are:
12.00
4546.54
.54
0.45

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

NSString *sepStr;

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count]>=2)
   {
        sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        NSLog(@"sepStr:%@",sepStr);
        if([sepStr length] >2)
       {
        return NO;
       }
    else 
       {
        return YES;
       }

   }
   return YES;
 }
2
  • @Gowtham: I just used your code and just put extra two lines.. It's working fine.. Ignore the NSLog..
    – Manu
    Oct 16, 2012 at 9:24
  • & Nitin I tried the above solution but it didn't work.. Have a make any changes? Feb 6, 2014 at 9:45
2

When a dot is entered, you should check whether a dot is present already, and return NO if it is present.

 NSString * newString = [textField.text stringByReplacingCharactersInRange: range withString: string];
 NSArray * sep = [newString componentsSeparatedByString: @"."];
 if([string isEqualToString:@"."] && [sep count] > 1){
    //already a . is  there.. so don't allow new one
    return NO;
 }
 if ([sep count] >= 2) {
     NSString * sepStr = [NSString stringWithFormat: @"%@", [sep objectAtIndex: 1]];
     NSLog(@"sepStr:%@", sepStr);

     return !([sepStr length] > 2);
 }
 return YES;
1

Updated answer for Swift 3 using the reg ex "^([0-9]*)(\\.([0-9]+)?)?$":

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)

    let expression = "^([0-9]*)(\\.([0-9]+)?)?$"

    guard let regex = try? NSRegularExpression(pattern: expression, options: .caseInsensitive) else {
        return false
    }
    let noOfMatches = regex.numberOfMatches(in: newText, options: [], range: NSMakeRange(0, newText.characters.count))

    return noOfMatches > 0
}
0

You can use this method:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSRange temprange = [textField.text rangeOfString:@"."];
        if ((temprange.location != NSNotFound) && [string isEqualToString:@"."])
        {
            return NO;
        }
    return YES;
}
0
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSArray *sep = [newString componentsSeparatedByString:@"."];
    if([string isEqualToString:@"."]){
        if([textField.text containsString:@"."]){
            return NO;
        }
    }
    if([sep count] >= 2)
    {
        NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        return !([sepStr length]>2);
    }
    return YES;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.