Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - iOS - verify float/double

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?

like image 827
Henry David Avatar asked Jun 16 '26 10:06

Henry David


2 Answers

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).

like image 25
wxactly Avatar answered Jun 18 '26 00:06

wxactly