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
an
Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration. This produces more compact, readable code, and also prevents you from inadvertently assigning a value to the variable before the method call.
bool isDouble = double.TryParse(yourString, out double result);
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
use this
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
You should use the TryParse method for the int
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:
public bool IsNumber(String value)
{
double d;
if (string.IsNullOrWhiteSpace(value))
return false;
else
return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out d);
}
It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any
does not include hex mumbers, because the type double does not support it.
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal
or double
.