Skip to content

Instantly share code, notes, and snippets.

@jonathan-beebe
Created February 15, 2013 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonathan-beebe/4962594 to your computer and use it in GitHub Desktop.
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
// 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
// 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