Question

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

Was it helpful?

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
}

OTHER TIPS

Convert to double and back to string. If it matches the source, then it was a double. Careful with leading and trailing spaces.

You can use the class NSScanner to find out if you got a valid double with this method :

- (BOOL)scanDouble:(double *)doubleValue

once you have initialized your scanner with your string.


Why (double *) ?
Because you want the method to return to you 2 informations, the doubleValue and is it a valid double. The latter is given by the BOOL and for the former only a Pointer can get you a value out of a method call (apart from the return value)

Parameters
doubleValue
Upon return, contains the scanned value. Contains HUGE_VAL or –HUGE_VAL on overflow, or 0.0 on underflow.
Return Value
YES if the receiver finds a valid floating-point representation, otherwise NO.

NSMutableString *stringElement = [NSMutableString stringWithCapacity:[yourString length]];
for (int i=0; i<[yourString length]; i++) {
    if (isdigit([stringElement characterAtIndex:i])) {
      //is digit
    }
}

Example:

NSError* error;
NSString* string=@"10";
NSNumberFormatter* formatter=[NSNumberFormatter new];
formatter.numberStyle= NSNumberFormatterDecimalStyle; // set whatever style you need
NSNumber* number;
if([formatter getObjectValue: &number forString: string errorDescription: &error])
{
    // You got the number
    NSLog(@"%@",number);
}
else
{
    // haven't got the number, the string is invalid
    NSLog(@"%@",error);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top