Converting string to int and then back to string

Viewed 297

I am trying to convert my string variable to an integer to add a value (+1) to it but the result I get is:

1111

Infact I should be getting a total of 4 when I reconvert it to string.

What am I doing wrong?

public string str_Val = "1";

void Update () {
if (str_Val  != "5") {
      str_Val  = int.Parse (str_Val + 1).ToString ();
   }
}
2 Answers

It's all about the priority of the actions:

int.Parse (str_Val + 1)

In the row above first the addition happens str_Val + 1 outputing 11,111,111 etc.

Then the parsing occurs changing "11" to 11

Then to string occurs changing 11 to "11"

So change your code to

str_Val  = (int.Parse(str_Val)+1).ToString();

This will first convert the string to int, then add two integers and finally convert the integer to string again.

you are concatenating 1 to the string before parsing, that is the reason of the behavior on your code...

so you are doing:

"1" + 1

"11"

Parse to int ("11")

convert to string(11)

do instead:

if (str_Val  != "5")
{
      str_Val  = (int.Parse(str_Val) + 1).ToString ();
   }
}
Related