Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two numbers concatenates them instead of calculating the sum

People also ask

Why is my JavaScript concatenating instead of adding?

JavaScript (+) sign concatenates instead of giving sum? The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.

How do I stop concatenation?

To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.

Why are my numbers not adding in JavaScript?

When you say prompt() it returns a string by default, so 12+12 is added like a string. You must cast the value to a number type and you can either use Number(prompt()) or parseInt(prompt()). Strings see '+' as concatenating operator.

How do you add two numbers in HTML?

You can then add numbers in the first two text boxes and store them in a variable such as "result," as follows: var result = Number(box1. value) + Number(box2. value); box3.


They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:

var x = +y + +z;

I just use Number():

var i=2;  
var j=3;  
var k = Number(i) + Number(j); // 5  

You need to use javaScript's parseInt() method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".


Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).

var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);

alert(x + y);

Hope this helps!