Thursday, June 09, 2005

C# string to number conversion

What do you do to convert a string to a number in C#? I use't to use the "number.Parse" methods, but these always need wrapping in a try...catch block, e.g.
bool ok = true;
int result = 0;
try
{
  result = int.Parse(sometext);
}
catch (Exception e)
{
  ok = false;
}
I turns out there is a way to do this without exceptions being involved, the double.TryParse method:
int result = 0;
double temp;
if (double.TryParse(sometext, NumberStyles.Integer, null, out temp))
  result = (int)temp;
else
  // not a valid number....

1 Comments:

Anonymous Anonymous said...

Or use Microsoft.VisualBasic.Information.IsNumeric()
[if you can bring yourself to reference the VB.NET "Runtime" (Microsoft.VisualBasic.dll)]

see:
http://www.hanselman.com/blog/ExploringIsNumericForC.aspx

4:35 pm  

Post a Comment

<< Home