2

I'd like to check a UITextfield to make sure it doesn't contain a second decimal. How do I check a NSString for a second decimal?

Really what I'd like to do is present a uitextfield and have just the number pad and make it so if the user presses 1 2 3 4 5 6 7 8 9 it shows up as "$1,234,567.89" however I run into issues converting the string to a float value and it rounding the result... but if I can just make sure that the user doesn't type 2 decimals I'll be good also.

Hackmodford
  • 3,901
  • 4
  • 35
  • 78
  • Please check this, http://stackoverflow.com/questions/276382/what-is-the-best-way-to-enter-numeric-values-with-decimal-points – AAV Jan 05 '12 at 19:13

1 Answers1

3

The best way to do this is to prevent the user from entering a second decimal point. Use the UITextFieldDelegate method – textField:shouldChangeCharactersInRange:replacementString: as follows

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"."];

    if ([string rangeOfCharacterFromSet:set].location != NSNotFound && [textField.text rangeOfCharacterFromSet:set].location != NSNotFound) {
        return NO;
    }

    return YES;
}

Now, if the user presses the decimal point again, it will not be added to the existing UITextField.

bbarnhart
  • 6,620
  • 1
  • 40
  • 60