Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify if a string is a number

If I have these strings:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

Is there a command, like IsNumeric() or something else, that can identify if a string is a valid number?

like image 906
Gold Avatar asked May 21 '09 18:05

Gold


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 .

How do you check if a string is a number in Python?

Python String isnumeric() Method The str. isnumeric() checks whether all the characters of the string are numeric characters or not. It will return True if all characters are numeric and will return False even if one character is non-numeric.

How do you check if a string is a number in C?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.


1 Answers

int n; bool isNumeric = int.TryParse("123", out n); 

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n); 

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _); 

The var s can be replaced by their respective types!

like image 57
mqp Avatar answered Oct 19 '22 23:10

mqp