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;I turns out there is a way to do this without exceptions being involved, the double.TryParse method:
int result = 0;
try
{
result = int.Parse(sometext);
}
catch (Exception e)
{
ok = false;
}
int result = 0;
double temp;
if (double.TryParse(sometext, NumberStyles.Integer, null, out temp))
result = (int)temp;
else
// not a valid number....

1 Comments:
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
Post a Comment
<< Home