Created
February 2, 2013 08:52
-
-
Save Tricertops/4696643 to your computer and use it in GitHub Desktop.
Three options how to validate `NSString` instance to contain numeric value.
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
NSString *theString; // You have a string. | |
/// Option 1: floatValue | |
if ([theString floatValue] != 0 || [theString hasPrefix:@"0.0"] || [theString isEqualToString:@"0"]) { | |
// theString should be number | |
} | |
/// Option 2: NSRegularExpression | |
NSRegularExpression *regexNumber = [NSRegularExpression regularExpressionWithPattern:@"^[-+]?[0-9]*\\.?[0-9]+$" | |
options:0 | |
error:nil]; | |
NSUInteger matches = [regexNumber numberOfMatchesInString:theString | |
options:0 | |
range:NSMakeRange(0, theString.count)]; | |
// in this case only zero or one match is possible, since the regex contains ^...$ | |
if (matches > 0) { | |
// theString is number | |
} | |
/// Option 3: NSDecimalNumber | |
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:theString | |
locale:[NSLocale currentLocale]; // use any locale | |
if (decimalNumber != [NSDecimalNumber notANumber]) { | |
// theString is number | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment