Search code examples
objective-ciosexceptionnumbersidentification

How to find out whether input is number or text in objective-c?


I've tried to search, but I think my google is skill is not good enough, so I'm asking a help from people. I'm scanning through a string and taking each element. I need to find out whether it's number or text. I did my checking in that way:

// Try to convert to double
@try{
double whatever=[myString doubleValue];

// If text is stored in myString, then it should throw an exception
} @catch (NSException *e){

// Do whatever I need, but here I know that it's text, not a number


}

However I found out that Objective-C doesn't throw an exception, it just returns 0. I can't rely on the fact that user won't use zero as an input, what should I do?

Thanks in advance and I'm pretty sure there are treads like this, I just didn't find them...


Solution

  • Try this:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    
    NSNumber *number = [formatter numberFromString:myString];
    
    if (number) {
      // it's a number
    } else {
      // it's not a number
    }