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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With