Mandy Weston
Mandy Weston

Reputation: 3625

Converting strings to integer in 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

Upvotes: 2

Views: 3399

Answers (6)

Simant
Simant

Reputation: 4400

string strNum= "003";
int myInt;
if( int.TryParse( myString, out myInt )
{
  //here you can print myInt
}else{
  //show error message if strNum is invalid integer string
}

Upvotes: 2

Serge Mikhailov
Serge Mikhailov

Reputation: 31

Here is it:

int i;

if ( Int32.TryParse("003", i) )
{
    // Now you have the number successfully assigned to i
}
else
{
    // Handle the case when the string couldn't be converted to an int
}

Upvotes: 1

Andrew
Andrew

Reputation: 5277

int i;
int.TryParse(stringValue, out i)

Upvotes: 0

Robert Williams
Robert Williams

Reputation: 1340

You need to parse the String to an Int

Int32.Parse("001");

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75679

int number = int.Parse(string)

or

int number;
int.TryParse(string, out number)

Upvotes: 2

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60734

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)
}

Upvotes: 7

Related Questions