Created
February 15, 2013 19:09
-
-
Save jonathan-beebe/4962594 to your computer and use it in GitHub Desktop.
Check if an NSString is numeric and/or contains only numeric characters. Inspired by StackOverflow
http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-numeric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by StackOverflow | |
// http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-numeric | |
#import <Foundation/Foundation.h> | |
@interface NSString (isNumeric) | |
- (BOOL) isAllDigits; | |
- (BOOL) isNumeric; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by StackOverflow | |
// http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-numeric | |
#import "NSString+isNumeric.h" | |
@implementation NSString (isNumeric) | |
- (BOOL) isAllDigits | |
{ | |
NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; | |
NSRange r = [self rangeOfCharacterFromSet: nonNumbers]; | |
return r.location == NSNotFound; | |
} | |
-(BOOL) isNumeric | |
{ | |
NSScanner *sc = [NSScanner scannerWithString: self]; | |
// We can pass NULL because we don't actually need the value to test | |
// for if the string is numeric. This is allowable. | |
if ( [sc scanFloat:NULL] ) | |
{ | |
// Ensure nothing left in scanner so that "42foo" is not accepted. | |
// ("42" would be consumed by scanFloat above leaving "foo".) | |
return [sc isAtEnd]; | |
} | |
// Couldn't even scan a float :( | |
return NO; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment