Detect if a string is s number

D

Danny Ni

Hi,

In C#, I have vaiables declared as string, how can I detect if they are
numeric? Like VB has IsNumeric function.

TIA
 
B

Barry Kelly

Danny Ni said:
In C#, I have vaiables declared as string, how can I detect if they are
numeric? Like VB has IsNumeric function.

Try to parse it with int.TryParse() or double.TryParse(). You can
discard the result. For example:

---8<---
public static bool IsNumeric(string value)
{
double unused;
return double.TryParse(value, out unused);
}
--->8---

Mind internationalization, if you need to always parse '.' as decimal
versus ',' etc.

-- Barry
 
M

Michael Nemtsev

Hello Danny,

Besides parsing, as Barry recomended, there are several other way

- Char.IsDigit for each char in string
- Use Regexp to check string

And look for this discussion there http://groups.google.com/group/micr..._frm/thread/3a72ac6eb7d88cc7/77a0af96fe705eba

DN> Hi,
DN>
DN> In C#, I have vaiables declared as string, how can I detect if they
DN> are numeric? Like VB has IsNumeric function.
DN>
DN> TIA
DN>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
C

coosa

Regex seems to be the most effecient and shortest way though; beside
the syntax would look very short.
For the suggestion of Char.IsDigit there might be an issue with
decimals, large exp, ..etc. to consider
 
M

Michael Nemtsev

Hello coosa,

c> Regex seems to be the most effecient and shortest way though; beside
c> the syntax would look very short.
c> For the suggestion of Char.IsDigit there might be an issue with
c> decimals, large exp, ..etc. to consider

There is one possible way, add reference to the Microsoft.VisualBasic and
use IsNumeric ;)

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 

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