0

I am working on a geometry style like calculator using javascript, and I need user input. But when the user, for example, inputs 55 and the other also 55 the sum of the number will be 5555 when I'd like it to be 110.

Javascript Code:

function ftmad2(){
    let angle1 = prompt("Please enter the first angle:");
    let angle2 = prompt("Please enter the second angle:");
    sumAngle = angle1 + angle2;
    console.log(sumAngle);
    let result = 180-sumAngle;
    document.getElementById("result").innerHTML = result;
}
Hikaru
  • 15
  • 5
  • If you read the [documentation at MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt) you will see that *"result is a string containing the text entered by the user, or null."*. So with that information you can see that you are concatenating strings, not adding numbers..... – epascarello Aug 28 '18 at 19:25

3 Answers3

1

Common issue; it is reading 55 as a string, rather than a number, do:

sumAngle = parseInt(angle1, 10) + parseInt(angle2, 10);
Chris Cousins
  • 1,862
  • 8
  • 15
0

Current senerio

"55"+"55"  //which will  return 5555 obviously

Use parseInt to convert string to int because your both value angle1 and angle2 coming in string format, you should convert into int before sum.

required senerio

   55 + 55  //which will return 110 

function ftmad2(){
    let angle1 = prompt("Please enter the first angle:");
    let angle2 = prompt("Please enter the second angle:");
    angle1 = parseInt(angle1);
    angle2 = parseInt(angle2);
    sumAngle = angle1 + angle2;
    console.log(sumAngle);
    let result = 180-sumAngle;
    document.getElementById("result").innerHTML = result;
}

ftmad2();
<p id="result"></p>
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
0

prompt() returns a string.

When you do angle1 + angle2 you're joining two strings instead of summing two numbers.

In order for this to work, you'll have to transform the strings in numbers first. Like this:

function ftmad2(){
    let angle1 = prompt("Please enter the first angle:");
    let angle2 = prompt("Please enter the second angle:");
    sumAngle = parseFloat(angle1) + parseFloat(angle2);
    console.log(sumAngle);
    let result = 180-sumAngle;
    document.getElementById("result").innerHTML = result;
}
ftmad2();
<div id="result"></div>
Phiter
  • 14,570
  • 14
  • 50
  • 84