I created a simple program that make the sum of two numbers BUT.. the program is concatenating instead, This is so confusing! Can anyone help?
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = numberOne + numberTwo;
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<!doctype html>
<html>
<body>
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
</body>
</html>
The reason that adding 2 numbers together in JavaScript is that one or more of the operands that we try to add together may not be numbers. Therefore, we should make sure that they're both numbers before trying to add them. To do this, we can convert to numbers with various functions or operators.
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.
To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.
Here value
gives you a string, hence the concatenation. Try parsing it as an Number instead:
var sum = parseInt(numberOne) + parseInt(numberTwo);
See the demo fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With