How to determine if a string represents a valid numerical value?

  • Thread starter Marc Scheuner [MVP ADSI]
  • Start date
M

Marc Scheuner [MVP ADSI]

Folks,

I need to try and make sure that a given string is a valid numerical
value (not just int, or int32 - it could be float, decimal, what have
you). VB.NET has a neat "IsNumeric" function - too bad C# doesn't have
anything similar. Or does it??

I was thinking about trying to convert the string to Int32, but as I
mentioned - that alone won't be good enough, and I really don't want
to attempt a dozen conversions to find out - nor do I really want to
start parsing the string for numerical characters (since there can be
"+", "-", "." and many more extra character and it's still a valid
numeric).

Any ideas? Thoughts?

Thanks!
Marc

================================================================
Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
 
P

Peter Rilling

Two ways. You can either try to convert the string in a try block. If an
exception is thrown, it is not a number.

Alternatively, you can reference the VB.NET assembly (which is located in
the references dialog) and use the IsNumeric function available to VB
developers.
 
J

Jim Frapper

I was thinking about trying to convert the string to Int32, but as I
mentioned - that alone won't be good enough, and I really don't want

Here are a few ways:

1. Pick the lowest common denominator. Cast it to a decimal.
2. Use a regex. There are plenty of places you can find the right pattern
if you dont know it.
3. Use a control that does it. In some cases in my windows.forms app I am
using the numeric up down control.
4. Catch the KeyDown event and check the input.
etc..
etc...

JF
 
L

Len Weaver

Hello Marc,
I need to try and make sure that a given string is a
valid numerical value (not just int, or int32 - it
could be float, decimal, what have you). VB.NET has
a neat "IsNumeric" function - too bad C# doesn't have
anything similar. Or does it??

The static Double.TryParse method may be of interest to you.

Hope this helps,
Len
 
M

Matt Moran

I think the easiest way would be to use a simple regular expression. I
have been using regular expressions and I have found them to be very
easy and extremely powerful and flexible. A great source for learing
them is Mastering Regular Expressions - and O Reily book or get it from
www.regexlib.com.

Matt
 
?

=?ISO-8859-1?Q?Thomas_Gagn=E9?=

Out of curiosity, what do you want back as the answer? A boolean? An
exception?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top