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.
Asked
Active
Viewed 4,400 times
1
-
possible duplicate of [How to convert an NSString into an NSNumber](http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber) – Dave DeLong Oct 06 '11 at 02:35
-
Thanks @Dave, I added that method and attribution to my answer. – zaph Oct 06 '11 at 03:00
2 Answers
7
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 :-))
-
For a the few weeks that I have spent in Objective C I will take any thing to avoid alloc\init.BTW `(I'm not leaking, I'm using ARC :-))`please elaborate might be handy tip for a beginner like myself. – Java Ka Baby Oct 06 '11 at 03:28
-
2Well, if `alloc/init` bother you so much you can use `new` albeit it is deprecated: NSNumberFormatter *formatter = `[NSNumberFormatter new];` but I don't suggest that. ARC (Automatic Referencing Counting), available in Xcode 4.2 and IOS 4.3 and above eliminates the need for `retain`, `release' or `autorelease`, in fact they are not allowed. OK, my comment: it is common to get a comment that a release is missing from a code snippet, my snarky comment was directed to that possibility, eventually we will need to come to grips with release/autorelease not being necessary in code under ARC. – zaph Oct 06 '11 at 03:36
-1
you can use [NSString floatValue]

Foo Bah
- 25,660
- 5
- 55
- 79
-
2
-
the question is not how to convert but how to check if the string can be converted to some numeric value – shebelaw Jan 27 '13 at 19:32