How can I check if a string is a number?
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?
Solution 1:
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)
Solution 2:
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);
Solution 3:
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Solution 4:
Use Int32.TryParse()
int num;
bool isNum = Int32.TryParse("[string to test]", out num);
if (isNum)
{
//Is a Number
}
else
{
//Not a number
}
MSDN Reference
Solution 5:
Use int.TryParse()
:
string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
result will be true
if it was.