#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Something I don't understand with += and -=

Hi, I use Twine 2.1.1 and sugarcube 2.14

I work on a textbox for a bank system (withdraw and deposit).

Here what I've got on the passage called "Bank" :
```Withdraw : <<textbox "\$Withdraw" "">>[[euros|Bank]]
Deposit : <<textbox "\$Deposit" "">>[[euros|Bank]]
```

and here what I've got in the display :
```\<<if passage() is "Bank">><<if \$Withdraw>><<set \$Money+=\$Withdraw; \$Baccount-=\$Withdraw>><</if>><<if \$Deposit>><<set \$Money-=\$Deposit; \$Baccount+=\$Deposit>><</if>><</if>>
```

The result for the -= is always good.

BUT, the result for the += set something weird.

For example :

\$Money is 10
\$Baccount is 1000

I withdraw 200, the result would be 210 and 800. No the result are 10200 and 800
Then I deposit 200, the result would be 10000 and 1000. No the result are 10000 and 800200

So maybe my setting is wrong, but I don't understand the result.

• edited March 2017
You need to convert the string type variable from the text box into a number type variable.

10 + "200" is "10200" while 10 + 200 is 210.

To change the type, add
```<<set \$Withdraw to parseInt(\$Withdraw, 10)>>
```

To your code before you do any math. Do the same thing for \$Deposit.

The reason -= is working is probably because JavaScript is fairly loosely typed, and its likely converting the string for you when it can't make sense of the operation otherwise. It's still best to change the type anyway, though, rather than relying on the browser to figure out what you mean.
• Hi,

Thanks a lot, it was a string value !!! damn it. Have a good day.
• Chapel is correct about needing a conversion. The <<textbox>> macro always yields a string, but you need it to be a number, so you have to convert the string into a number—as shown by Chapel.

The reason why the -= operator works as expected and the += operator doesn't here has to do with what roles they play. The -= operator is only the number subtraction assignment operator—i.e. it only does arithmetic. The += operator, on the other hand, is both the number addition assignment operator and the string concatenation assignment operator—i.e. it does arithmetic and concatenation. In computer science terms, the += operator is overloaded—the + operator is overloaded similarly.

When the left-hand and right-hand sides are both numbers, there's no ambiguity, do arithmetic.

When the left-hand and right-hand sides are both strings, there's no ambiguity, do concatenation.

When one of the sides is a number and the other is a string, then there's ambiguity. In this case, the default choice is concatenation.