1

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)
2
  • I don't normally do that, but, wtf?! Commented Nov 25, 2011 at 12:44
  • c will be a number, unless you do something like c = a + '' + b; Commented Nov 25, 2011 at 12:46

5 Answers 5

3

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; 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Your code works fine. See here.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.