IS Numeric

You could use regular expressions to validate the string (search these forums and you'll will find a few samples), or alternatively you may want to use the double.TryParse(...) method - incidently if you look at the VB IsNumeric function in ildasm then it actually calls the TryParse method itself anyway....
 
Something like:

internal static double IsNumeric(object oValue)
{
try
{
if (oValue == null || System.Convert.IsDBNull(oValue))
return false;

string sString = oValue.ToString().Trim();

double dValue=0;
if (double.TryParse(sString, NumberStyles.Any,
CultureInfo.CurrentCulture, out dValue))
return true;
else
return false;
}
catch
{
return false;
}
}
 
Just reference Microsoft.VisualBasic and you can use the VB IsNumeric function in C#.

Otherwise, just do something like this:
Code:
private bool IsNumeric(object o)
{
    try { double d = Convert.ToDouble(o); return true; }
    catch { return false; }
}
 
Tamer_Ahmed said:
hi in VB.net i can use ISNumeric to determine if it's numeric or not but in C# i can't use it can any body help

Try this out Tamer:

Code:
    Public Overloads Function IsNumeric(ByVal Value As Object) As Boolean
        Dim RegEx As Regex

            If Not Value Is Nothing Then
                RegEx = New Regex("(\+|-)?[0-9][0-9]*(\.[0-9]*)?")
                If RegEx.IsMatch(Value.ToString) AndAlso RegEx.Match(Value.ToString).Length = CType(Value, String).Length Then
                    Return True
                Else
                    Return False
                End If
            Else
                Return False
            End If

  End Function

You should be able to easily convert this to c#.
 
Although the regex works it does have a locale bias (assumes .) as decimal seperator, and will fail if a thousands seperator is specified (or if a trailing +/- is used).
Also it will not cope with currency or non decimal (e.g. hex) numbers.

Using double.TryParse like I suggested an Jaco showed how to do in a previous post in this thread is a easy enough way to do this.
 
Back
Top