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

风格不统一 提交于 2019-12-23 03:12:56

问题


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.


回答1:


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 :-))




回答2:


you can use [NSString floatValue]



来源:https://stackoverflow.com/questions/7669569/how-to-check-if-contents-of-a-string-are-numeric-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!