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
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.
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
EDIT: As Lukas 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 num)
Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:
using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.
string num = "123x";
foreach (char c in num.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("character " + c + " is not a number");
return;
}
}
int num;
bool isNumeric = int.TryParse("123", out num);
public static void Main()
{
string id = "141241";
string id1 = "232a23";
string id2 = "12412a";
validation( id, id1, id2);
}
public static void validation(params object[] list)
{
string s = "";
int result;
string _Msg = "";
for (int i = 0; i < list.Length; i++)
{
s = (list[i].ToString());
if (string.IsNullOrEmpty(s))
{
_Msg = "Please Enter the value";
}
if (int.TryParse(s, out result))
{
_Msg = "Enter " + s.ToString() + ", value is Integer";
}
else
{
_Msg = "This is not Integer value ";
}
}
}
I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.
private bool IsValidNumber(string _checkString, string _checkType)
{
float _checkF;
int _checkI;
bool _result = false;
switch (_checkType)
{
case "int":
_result = int.TryParse(_checkString, out _checkI);
break;
case "float":
_result = Single.TryParse(_checkString, out _checkF);
break;
}
return _result;
}
I simply call this with something like:
if (IsValidNumber("1.2", "float")) etc...
It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.