开发者

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

开发者 https://www.devze.com 2023-04-10 19:52 出处:网络
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;

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

精彩评论

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

关注公众号