Reputation: 20163
How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
Upvotes: 1
Views: 295
Reputation: 154828
The most concise way is prepending a +
if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123
etc.
Upvotes: 0
Reputation: 26492
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
Upvotes: 0
Reputation: 175766
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Upvotes: 3
Reputation: 490203
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String
. In your example, both are Number
.
If you do have numbers inside of String
s, you can use parseInt()
(don't forget to pass the radix of 10
if working in decimal) or possibly just prefix the String
with +
to coerce it to Number
.
Upvotes: 0