Skip to content Skip to sidebar Skip to footer

Javascript (+) Sign Concatenates Instead Of Giving Sum?

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?

Solution 1:

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.

Solution 2:

Javascript takes dom elements as string only by default. To make mathematical calculation, you need to typecast it to integer/float or convert to number.

parseInt(number) = number, truncates after decimal value
parseFloat(number) = numberwith decimal values
Number(number) = numberwith or without decimal

Solution 3:

Your numberOne and numberTwo are strings, so you get concatenated strings when use + sign with two string. Parse first to numbers then sum them. You can use parseInt() and parseFloat() functions for it.

var numberOne = '7';
var numberTwo = '8';

var sum = numberOne + numberTwo;
console.log(sum);

sum = parseFloat(numberOne) + parseFloat(numberTwo);
console.log(sum);

Solution 4:

Use parseInt() for this, Check snippet below

functioncalculate() {
    var numberOne = document.querySelector(".first").value;
    var numberTwo = document.querySelector(".second").value;
    var sum = parseInt(numberOne) + parseInt(numberTwo);
    document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
  }
<p>Calculate sum of two numbers !</p>
  Enter 1rst Number:<br><inputtype="number"class="first"placeholder=""><br><br>
  Enter 2nd Number:<br><inputtype="number"class="second"placeholder=""><br><br><inputtype="button"onclick="calculate()"value="calculate"><pclass="result"></p>

Solution 5:

Example , you can use this:

varnumberOne:number = +document.querySelector(".first").value;
varnumberTwo:number = +document.querySelector(".second").value;
var sum = numberOne + numberTwo;

You should use + Angular typeScript

Post a Comment for "Javascript (+) Sign Concatenates Instead Of Giving Sum?"