Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to int and then back to string [closed]

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 ();
   }
}
like image 381
Naik Avatar asked Nov 16 '25 09:11

Naik


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.

like image 170
Athanasios Kataras Avatar answered Nov 18 '25 23:11

Athanasios Kataras


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 ();
   }
}
like image 45
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 19 '25 00:11

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!