0

I was trying to make a really simple & basic calculator with JS. For the "addition" portion of the calculator the numbers that are put in won't add properly... FOR EXAMPLE: 12 + 12 comes out as "1212" not 24 OR 6 + 15 comes out as "615" not 21 Can anyone tell me why?

<!DOCTYPE html>
<html>
<head>
<button onclick="Divide()">Divide</button> </br>
<button onclick="Multiply()">Multiply</button> </br>
<button onclick="Add()">Add</button> </br> 
<button onclick="Subtract()">Subtract</button> </br>
    <script>
    function Divide (){
        var dividend = prompt("What is the dividend?")
        var divisor = prompt("What is the divisor")
        var answer = prompt(dividend / divisor)
    }
    function Multiply (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 * Number2)
    }
        function Subtract (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 - Number2)
    }
    function Add (){
        var Number1 = prompt("What is the first number")
        var Number2 = prompt("What is the second number")
        var answer = prompt(Number1 + Number2) 
    }

</script>


</head>
<body>

</body>
</html>
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Conner
  • 1
  • 1
  • You need to coerce the values provided by `prompt` into numbers. You can use `Number`, for example: `prompt(Number(Number1) * Number(Number2))`. – Ivan May 25 '19 at 17:58
  • 4
    Possible duplicate of [How to add two strings as if they were numbers?](https://stackoverflow.com/questions/8976627/how-to-add-two-strings-as-if-they-were-numbers) – Anurag Srivastava May 25 '19 at 17:58
  • Concatenating strings instead of summing integers – admcfajn May 25 '19 at 20:44

1 Answers1

0

Javascript is taking user input as string data. The + symbol concatenates strings. For addition, you want to convert the string data to integers with parseInt():

var answer = prompt(parseInt(Number1) + parseInt(Number2));

Scott Flodin
  • 320
  • 1
  • 5