Maxime
Maxime

Reputation: 3165

Detect if NSString is a float number

I am trying to dectect if an NSString it's a float number, for exemple : @"-73.041382"

But when I try with this method I obtain a wrong result:

-(bool) isNumeric:(NSString*) checkText{

NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:checkText];
if (number != nil) {
    return true;
}
return false;

}

Someone have an idea!?

Thanks

Upvotes: 7

Views: 3980

Answers (2)

Seega
Seega

Reputation: 3390

-(bool) isNumeric:(NSString*) checkText{
   return [[NSScanner scannerWithString:checkText] scanFloat:NULL];
}

i'm currently not on mac so i can't check it, hope it helps

Upvotes: 7

Maxime
Maxime

Reputation: 3165

I have found the answer :

-(bool) isNumeric:(NSString*) checkText{

NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
//Set the locale to US
[numberFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
//Set the number style to Scientific
[numberFormatter setNumberStyle:NSNumberFormatterScientificStyle];
NSNumber* number = [numberFormatter numberFromString:checkText];
if (number != nil) {
    return true;
}
return false;
}

Thanks!

Upvotes: 10

Related Questions