IsNumeric

  • Thread starter Thread starter Tom
  • Start date Start date
T

Tom

I need a way (Server Side) to check if a text box's value
is numeric or not.

Can anyone assist?

Thanks

Tom
 
Tom,

If you want to use the IsNumeric function that comes with VB, then you
can set a reference to Microsoft.VisualBasic.dll in your project. IsNumeric
is defined as a static method on the Information class in the
Microsoft.VisualBasic namespace.

However, if you want a more ".NET" way (which isn't linked explicitly
for VB, some people have issue with this), you can use the static TryParse
method on the Double value type. This will attempt to parse a string, but
you will have to be a little more specific about what is acceptable and what
is not (through the use of number styles).

Hope this helps.
 
Tom, here are a couple of ways to do this:

1 Use the Parse method on any of the Int32, Int64, etc classes. If it
throws an exception it's not numeric.
2. Add a reference to the Microsoft.VisualBasic.dll assembly and then use
the IsNumeric function on the Microsoft.VisualBasic.Information class.
3. Write a regex statement that checks whether the string has anything but
numbers.

Hope that helps.
 
Hi Tom,

You could use a RegEx for this, here is one I'm using you may need to change
it to your needs

Regex r = new Regex(@"\d+|\d+\.\d+");
r.IsMatch( stringToTest );

basically it will test true for a construction like XXX.YYY with any number
of decimal places on each side of the "."

You could also try to use Convert.ToDouble|ToInt32 , etc and put it inside a
try/catch block

Cheers,
 
Ignacio Machin:

Thanks for your reply. Can you tell me where I can get
more information on regular expressions as your example is
not exactly what I am looking for but close.

I'm not familiar with Regex(@"\d+|\d+\.\d+") this.

Thanks
Tom
 
Seeing as noone mentioned this, and even though I'm not sure how it would
perform ...

string numeric = "0123456789"
string num = textBox.Text;
for(int x = 0; x < num.Length; x++)
{
if( numeric.IndexOf(num[x]) == -1 )
{
// not a number, one of the characters was not 0 1 2 3 4 5 6 7 8 9
}
}

If you want a decimal point, add "." or "," to numeric.
Use a bool flag to make sure there is only one.
 
Back
Top