-1

I am using the prompt() function and asking for users to enter 2 numbers which I then want to calculate the sum and return the answer on an alert.

var numOne = prompt('Give me a number'); 
var numTwo = prompt('Give me another number'); 
alert('The sum of your numbers is ' + numOne+numTwo);

It seems that javascript is using the numbers as strings and just returning a result with the 2 numbers side by side in a string??

Joe Godwin
  • 33
  • 1
  • 6
  • 2
    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) – misorude Sep 06 '19 at 06:25

2 Answers2

2

The prompt() method only returns a string.

You have to convert the string to a number using these methods:

  • Number()
  • parseInt()
  • parseFloat()

Generally you can use Number() method.

Add a sum variable and store the sum result of the numbers to it. The code is given below:

var numOne = prompt('Give me a number'); 
var numTwo = prompt('Give me another number'); 
var sum = Number(numOne) + Number(numTwo);
alert('The sum of your numbers is ' + sum);
Ranjith
  • 137
  • 1
  • 1
  • 7
0

Try

alert('The sum of your numbers is ' + (parseInt(numOne)+ parseInt(numTwo));

or

var numOne = parseInt(prompt('Give me a number')); 
var numTwo = parseInt(prompt('Give me another number')); 
alert('The sum of your numbers is ' + numOne+numTwo);
Pratik
  • 1,351
  • 1
  • 20
  • 37