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}`);

5 Answers 5

1

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

Comments

1

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}`);

1 Comment

numbers can be double
0

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

Comments

0

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

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

Comments

0

An other idea is to use parseInt()

const sum = parseInt(num1) + parseInt(num2)
console.log(`Sum of ${num1} and ${num2} is ${sum}`)

here a working code

let num1 = 50
let num2 = "5" //in case of string value the value will be converted by parseInt()
const sum = parseInt(num1) + parseInt(num2)
console.log(`Sum of ${num1} and ${num2} is ${sum}`)

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.