I have text field with placeholder 00.00 . I want to enter number in that format. Please help
Asked
Active
Viewed 3,018 times
-2
-
You want to enter or you want user to enter and validate in given format? – Anoop Vaidya Feb 25 '13 at 09:55
-
1possible duplicate of [Validate Numeric Input to UITextField as the User Enters Input](http://stackoverflow.com/questions/9344159/validate-numeric-input-to-uitextfield-as-the-user-enters-input) – trojanfoe Feb 25 '13 at 10:09
2 Answers
0
Make keyboard type numeric. And internally use below code to get double value
NSString *value =textfield_name.text;
double doubleValue = [value doubleValue];

python
- 1,407
- 1
- 15
- 31
0
Try this way:
Make your class the delegate for yourTextField
, and add the codes as used from here.
NSString *enteredValue=@"99.129";//get your value from textfield as yourField.text
double doubleValue=[enteredValue doubleValue];
NSString *formattedDoubleValue=[NSString stringWithFormat:@"%.2f",doubleValue];
NSLog(@"->%@",formattedDoubleValue);//now you can set back to the textfield as yourField.text=formattedDoubleValue
Alternatively, you can use NSNumberFormatter for this.
NSNumberFormatter *numFormatter=[NSNumberFormatter new];
[numFormatter setFormat:@"00.00"];
NSString *str=[numFormatter stringFromNumber:@99.129];
NSLog(@"->%@",str);
EDIT: As per your comment
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == self.yourTextField){
NSLog(@"here");
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^([0-9]{1,2})(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches==0){
return NO;
}
}
return YES;
}

Community
- 1
- 1

Anoop Vaidya
- 46,283
- 15
- 111
- 140