I have an iOS app with a UITextField
that allows the user to enter a number in. How can I ensure that the value the user types in is a valid number (either whole or decimal). Here is what I have tried, but for some reason it won't work for decimal numbers:
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([numString rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
NSLog(@"valid number");
}
else {
NSLog(@"invalid number");
}
If I enter a decimal number such as 435.634, the above code returns "invalid number" in the console log. I don't understand why this isn't working as I am using decimalDigitCharacterSet
?
Thanks to @rmaddy for helping me out, here is the solution I am using in case anyone is interested:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [formatter numberFromString:inputNumString];
if (myNumber != nil) {
NSLog(@"valid number");
}
else {
NSLog(@"invalid number");
}
This will work even if the number is whole or decimal. It also works with different locale decimal characters such as ,