How to check if a string contains a valid number, given the formats of localized numbers.
This question is not a primary one regarding number conversion. I can do this with NSNumberFormatter. And if I can’t, then I don’t even need to do this, and I can leave the line as a line. But I need to check if it contains a valid number.
By the way, we are in the middle of the textField: shouldChangeCharactersInRange: ... delegate method. Here I want to prevent the input of invalid characters by returning NO.
This is the code I have:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // Only test for numbers if it is a certain text field. if (textField == self.numValueTextField) { NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string]; // The user deleting all input is perfectly acceptable. if ([resultingString length] == 0) { return true; } double holder; NSScanner *scan = [NSScanner scannerWithString: resultingString]; BOOL isNumeric = [scan scanDouble: &holder] && [scan isAtEnd]; if (isNumeric) { [self.detailItem setValue:number forKey:kValueDouble]; } return isNumeric; } return YES; // default for any other text field - if any. }
This works great, but it means English notation. Floating point value must be pont. But it can be a comma or something in some parts of the world.
I know how to test certain characters. So I could check 0-9, comma and period. But is there a “right” way to do this?
If this is important: I'm on iOS.
source share