Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Created February 2, 2013 08:52
Show Gist options
  • Save Tricertops/4696643 to your computer and use it in GitHub Desktop.
Save Tricertops/4696643 to your computer and use it in GitHub Desktop.
Three options how to validate `NSString` instance to contain numeric value.
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