How to check if a string contains a valid number considering localized number formats.
This question is not primary about converting a number. I can do that with NSNumberFormatter. And if I can't then I don't even need to do it and can leave the string as string. But I need to check whether it contains a valid numer.
BTW, we are in the middle of a textField:shouldChangeCharactersInRange: ... delegate method. Here I want to prevent keying in illegal characters by returning NO.
This is the code that 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.
}
That works fine but it implies English notations. Meaning the floating point must be a pont. But it could be a comma or whatever in certain parts of the world.
I do know how to check for certain characters. So I could check for 0-9, comma and point. But is there a 'proper' way of doing that?
If it is of importance: I am in an iOS environment.