How do I add numbers that have been inputted on JavaScript?

2616 views javascript
0

So, my code is allowing the user to input 2 numbers, num1 and num2. However the addition function is concatenating the numbers rather than adding them. How can I fix this please?

Here is a snippet of the function:

var sum= num1 + num2;
alert(`Sum of ${num1} and ${num2} is ${sum}`);

answered question

5 Answers

5

The value is of type string. That's why the string concatenation is happening. To perform arithmetic operation, you have to convert the value to number.

Change

var sum= num1 + num2;

To

var sum= Number(num1) + Number(num2);

posted this
5

You can try turning the strings into numbers:

var sum = +num1 + +num2;

posted this
4

you need to cast strings to numbers, + sign is concatenating strings, here are the examples

var sum= Number(num1) + Number(num2);
alert(`Sum of ${num1} and ${num2} is ${sum}`); // Sum of 1 and 2 is 3

or

var sum= +num1 + +num2;
alert(`Sum of ${num1} and ${num2} is ${sum}`); // Sum of 1 and 2 is 3

posted this
6

That is because the even though the input type is number the value is in form of a string, and instead of adding it, it will concating the values.Convert them to number before adding it

var sum = Number(num1) + Number(num2);
alert(`Sum of ${num1} and ${num2} is ${sum}`);

posted this
13

You can force it to string and use "" + num1 + num2

var sum = "" + num1 + num2;
alert('Sum of ${num1} and ${num2} is ${sum}');

posted this

Have an answer?

JD

Please login first before posting an answer.