How to check if IsNumeric [duplicate]
Possible Duplicate:
How to identify if string contain a number?
In VB there's an IsNumeric function, is there something similar in c#?
To get around it, I just wrote the code:
if (Int32.Parse(txtMyText.Text.Trim()) > 0)
I was just wondering if there is a better way to do this.
You could write an extension method:
public static class Extension
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
You should use TryParse
- Parse
throws an exception if the string is not a valid number - e.g. if you want to test for a valid integer:
int v;
if (Int32.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
If you want to test for a valid floating-point number:
double v;
if (Double.TryParse(textMyText.Text.Trim(), out v)) {
. . .
}
Note also that Double.TryParse
has an overloaded version with extra parameters specifying various rules and options controlling the parsing process - e.g. localization ('.' or ',') - see http://msdn.microsoft.com/en-us/library/3s27fasw.aspx.
I think you need something a bit more generic. Try this:
public static System.Boolean IsNumeric (System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Hope it helps!
There's the TryParse method, which returns a bool indicating if the conversion was successful.
Other answers have suggested using TryParse
, which might fit your needs, but the safest way to provide the functionality of the IsNumeric
function is to reference the VB library and use the IsNumeric
function.
IsNumeric
is more flexible than TryParse
. For example, IsNumeric
returns true
for the string "$100"
, while the TryParse
methods all return false
.
To use IsNumeric
in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information
class, so assuming you have using Microsoft.VisualBasic;
, you can do this:
if (Information.IsNumeric(txtMyText.Text.Trim())) //...