I am working on the infamous Stanford calculator assignment. I need to verify inputted numbers for valid float values, so we can handle numbers like 102.3.79.
To avoid having to write a little loop to count periods in the string, there's got to be a built-in function yeah?
You can use the C standard library function strtod(). It stops where it encounters an error, and sets its output argument accordingly. You can exploit this fact as follows:
- (BOOL)isValidFloatString:(NSString *)str
{
const char *s = str.UTF8String;
char *end;
strtod(s, &end);
return !end[0];
}
There's at least one fairly elegant solution for counting @"." in a string:
NSString *input = @"102.3.79";
if([[input componentsSeparatedByString:@"."] count] > 2) {
NSLog(@"input has too many points!");
}
Digging a little deeper... If you're looking to validate the whole string as a number, try configuring an NSNumberFormatter and call numberFromString: (NSNumberFormatter documentation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With