Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting strings to integer in c#

Tags:

c#

I just asked a question about how to convert a number to a string with leading zeros. I had some great answers. Thanks so much. I didn't really know which to mark correct as they were all good. Sorry for the people I didn't mark correct.

Now I have strings like

001
002
003

How do I convert back to integers? something like the opposite of Key = i.ToString("D2");

Mandy

like image 350
Mandy Weston Avatar asked Nov 27 '25 09:11

Mandy Weston


1 Answers

Quite easy that also.

string myString = "003";
int myInt = int.Parse( myString );

If you aren't sure if the string is a valid int, you can do it like this:

string myString = "003";
int myInt;
if( int.TryParse( myString, out myInt )
{
  //myString is a valid int and put into myInt
}else{
  //myString could not be converted to a valid int, and in this case myInt is 0 (default value for int)
}
like image 194
Øyvind Bråthen Avatar answered Nov 29 '25 23:11

Øyvind Bråthen