检测NSString是否为浮点数

时间:2011-08-22 20:44:04

标签: ios

我试图检测NSString是否为浮点数,例如:@“ - 73.041382”

但是当我尝试使用这种方法时,我得到了错误的结果:

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

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

}

有人有想法!?

由于

2 个答案:

答案 0 :(得分:10)

我找到了答案:

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

谢谢!

答案 1 :(得分:7)

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

我目前不在Mac上,所以我无法检查它,希望它有所帮助