开发者

How to check if contents of a string are numeric values?

I have seen this 开发者_高级运维question but it is 2 years old. Is there a better\easier\newer way to check if string has numeric values. e.g 1 or 1.54 or -1 or -1.54 etc etc.


bool status;
NSScanner *scanner;
NSString *testString;
double result;

scanner = [NSScanner scannerWithString:testString];
status = [scanner scanDouble:&result];
status = status && scanner.scanLocation == string.length;

If status == YES then the string is fully numeric.

Or as @Dave points out from this SO answer:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
number = [formatter numberFromString:string];
status = number != nil;

(I'm not leaking, I'm using ARC :-))


you can use [NSString floatValue]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜