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?
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.
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 .
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.
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() .
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With