Jananni M Jananni M - 6 months ago 15
iOS Question

How to restrict two digits after decimal point

I need to allow user to type only two digits after the decimal point .

I just tried the following code but i am not getting exact result.

- (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;
}


i am getting following result for above code: 123.12.1233

But i need result like 1)1234.12 2)12.23

Note: I am using number keypad as keyboard input view.

Answer

I have have modified your code. Try this

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count] >= 2)
{
    NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
    if (!([sepStr length]>2)) {
        if ([sepStr length]==2 && [string isEqualToString:@"."]) {
            return NO;
        }
        return YES;
    }
    else{
        return NO;
    }
}