Abhinav Abhinav - 1 year ago 83
Objective-C Question

Finding out whether a string is numeric or not

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSString *newString = [myString substringWithRange:NSMakeRange(2,3)];

Answer Source

Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    // newString consists only of the digits 0 through 9

See +[NSCharacterSet decimalDigitCharacterSet] and -[NSString rangeOfCharacterFromSet:].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download