Search code examples
objective-cxcode4

How to check if contents of a string are numeric values?


I have seen this question but it is 2 years old. Is there a better\easier\newer way to check if string has numeric values. e.g 1 or 1.54 or -1 or -1.54 etc etc.


Solution

  • bool status;
    NSScanner *scanner;
    NSString *testString;
    double result;
    
    scanner = [NSScanner scannerWithString:testString];
    status = [scanner scanDouble:&result];
    status = status && scanner.scanLocation == string.length;
    

    If status == YES then the string is fully numeric.

    Or as @Dave points out from this SO answer:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    number = [formatter numberFromString:string];
    status = number != nil;
    

    (I'm not leaking, I'm using ARC :-))