Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if NSString is a float number

Tags:

ios

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

like image 336
Maxime Avatar asked Aug 22 '11 20:08

Maxime


2 Answers

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!

like image 166
Maxime Avatar answered Oct 15 '22 04:10

Maxime


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

like image 32
Seega Avatar answered Oct 15 '22 04:10

Seega