Double.TryParse returns a value, and I don't need a value. I need to be able to tell if a string is numeric and just return a bool.
is there a way to do this?
Double.TryParse returns a value, and I don't need a value. I need to be able to tell if a string is numeric and just return a bool.
is there a way to do this?
One way is to add a reference to Microsoft.VisualBasic
and then use Information.IsNumeric().
using Microsoft.VisualBasic;
...
if (Information.IsNumeric("1233434.0"))
{
Console.WriteLine("Yes");
}
Well, you could use a regular expression, but why not just discard the value from Double.TryParse and move on? I don't think it will be worth the effort trying to duplicate this code.
How about a regular expression?
string s = "13.2";
bool bIsDecimal = Regex.IsMatch("^-?\d+(\.\d+)?$");
should test whether it is a decimal value. What it won't tell you is whether it is a valid decimal, as in, will the number fit in the range of a decimal.
I would consider exactly what you need to determine. "Is numeric" is vaguer than it sounds at first. Consider the following strings, and whether you'd want to consider them numeric:
Using Double.TryParse
(with an en-GB culture - don't forget about cultural issues!) will give you True, False, True, True (despite it not being representable), True, False. True, True.
If you want to tell whether a later call to Double.TryParse
would succeed, calling it here will be the most accurate solution. If you're using some other criteria, a regular expression may well be more appropriate. An example of the criteria you might use:
That would disallow all but the fourth and last examples above.
EDIT: I've now noticed the title of the question includes "integer". That pretty much reduces the specification checks to:
I just fired up Visual Studio Express (both 2005 and 2008). The Intellisense says that the return value of Double.TryParse() is a bool. The following worked for me under limited testing...
double res; // you must be under very resource-constrained
// conditions if you can't just declare a double
// and forget about it
if (Double.TryParse(textBox1.Text, out res)) {
label1.Text = "it's a number";
} else {
label1.Text = "not a number";
}
Hi,
try this isnumeric:
public static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}