Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)]; 
like image 290
Abhinav Avatar asked May 22 '11 23:05

Abhinav


People also ask

How do you check if a string is an integer?

The most efficient way to check if a string is an integer in Python is to use the str. isdigit() method, as it takes the least time to execute. The str. isdigit() method returns True if the string represents an integer, otherwise False .

Is a string a numeric value?

The term "numeric string" just means that it is a numeric value, stored inside a string variable. These are all considered "numeric strings" because they are strings that represent numeric values.

How do you check if there is a number in a string Java?

Use the isDigit() Method to Check if String Contains Numbers in Java. To find an integer from a string, we can use this in-built function called isDigit() .


2 Answers

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:].

like image 148
John Calsbeek Avatar answered Oct 03 '22 03:10

John Calsbeek


I'd suggest using the numberFromString: method from the NSNumberFormatter class, as if the number is not valid, it will return nil; otherwise, it will return you an NSNumber.

NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease]; BOOL isDecimal = [nf numberFromString:newString] != nil; 
like image 33
Sam Avatar answered Oct 03 '22 04:10

Sam