virindh virindh - 2 years ago 114
Objective-C Question

How do I prevent more than 2 numbers after a decimal point in UITextField?

Right Now I am making an app where the user is required to input a currency value, decimal point optional, into a UITextField. My problem comes up when I try to prevent more than 2 numbers after a given decimal point while at the same time preventing more than one decimal point. I have researched around the web and couldn't find an exact answer. I have found that I will most probably need to use the shouldChangeCharactersInRange, but I'm not sure how to use it exactly...

Virindh Borra

Answer Source

You would use a number formatter:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:@"###0.##"];
NSString *formattedNumberString = [numberFormatter stringFromNumber:@122344.4563];
NSLog(@"formattedNumberString: %@", formattedNumberString);
// Output for locale en_US: "formattedNumberString: formattedNumberString: 122,344.45"


You would put this in one of your UITextFieldDelegate methods like textField:shouldChangeCharactersInRange:replacementString:. Get the most recent string by doing: NSString *s = [textField.text stringByReplacingCharactersInRange:range withString:string]; Then you would get the number value of that string with @([s floatValue]), and then use the number formatter like shown above, then put it in the text field.

I would do some checking to make sure they have entered in at least two digits after the decimal before messing with their input. But this would be the correct, localized way to do it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download