Q: convert to numbers

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

string newStr=myStr.Substring(1,3);
int newNum = System.Convert.ToInt32(newStr);

This fails if newStr does not have all characters as numbers. How can you do
this in a professional way?

Thanks,
Jim.
 
int newNum;
try
{
newNum=Convert.ToInt32(newStr);
}
cacth
{
newNum=0; //Or other default value
}
 
You can check if it is a number by using Int32.Parse() and a try/catch. If
it raises an exception, you handle it and it isn't a number.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 
You'll have to place the Convert.ToInt32 call inside of a try / catch
block. In 2.0 there will be TryParse methods that don't throw.
 

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

Back
Top