Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

how to prevent chain when adding javascript variables containing numbers

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

Answers (5)

pimvdb
pimvdb

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

Jon Newmuis
Jon Newmuis

Reputation: 26492

JavaScript will always do the latter, as long as both of the variables you are adding are numbers.

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35822

Your code works fine. See here.

Upvotes: 0

Alex K.
Alex K.

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

alex
alex

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 Strings, 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

Related Questions