0

Hey I am using a UITextField to take float value inputs. I am facing a difficulty as I want to restrict during run time, the precision of the values that a user can enter to 2 decimal places. For eg:

Values like 1.11,11.11, 111.11, 1111.11 are permissible and Values like 1.123, 1.111, 1.1111 are not

How could I achieve this without writing too much code. So basically as the decimal point precision hits 2 the user should not be able to increase it to 3. The input field should stop editing there.

3 Answers3

2

Make use of UITextFieldDelegate protocol and implement textField:shouldChangeCharactersInRange:replacementString:

Whenever a character is entered this method is called so in this method check if the entered character is '.' then allow entering only two digits after '.'

From this SO question how to validate textfield that allows two digits after

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

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

    NSArray *sep = [newString componentsSeparatedByString:@"."];
    if([sep count]>=2)
    {
        NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        return !([sepStr length]>2);
    }
    return YES;
}
Community
  • 1
  • 1
visakh7
  • 26,380
  • 8
  • 55
  • 69
0

You can have a counter which will be incremented after . is entered and of the counter is greater than 2 => return no :

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

if(string isEqualToString:@"." )
{
 counter++;
}
if(counter>2)
{
    return NO;
}
else
{
return YES;
}

}

make counter a global variable.

Ashwin G
  • 1,570
  • 1
  • 16
  • 23
0

see Restrict UITextField size

Community
  • 1
  • 1
iOSPawan
  • 2,884
  • 2
  • 25
  • 50
  • this doesn't help in dynamic cases. A user should be allowed to enter 1.11 and also 111111.11 but not 1.111 –  Mar 22 '11 at 08:34