Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string is a number?

Tags:

c#

I'd like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes 232a23   No 12412a   No 

and so on...

Is there a specific function?

like image 992
markzzz Avatar asked Jul 18 '11 13:07

markzzz


People also ask

How do you check if a string is an integer?

To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits.

How do you know if a string is a number Python?

Python String isnumeric() MethodThe isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

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.

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

Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.

string candidate = "3.14159"; if (double.TryParse(candidate, out var parsedNumber)) {     // parsedNumber is a valid number! } 

EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:

double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)

like image 177
James McCormack Avatar answered Oct 05 '22 17:10

James McCormack


If you just want to check if a string is all digits (without being within a particular number range) you can use:

string test = "123"; bool allDigits = test.All(char.IsDigit); 
like image 31
BrokenGlass Avatar answered Oct 05 '22 17:10

BrokenGlass