2

How do you take 2 numbers from the User with window.prompt and add them up without concatenating?

What I thought was:

var temp = window.prompt("Number1")
var temp2 = window.prompt("Number2")
var answer = temp + temp2;
document.write(answer);

but it only concatenates not adds.

5 Answers5

8

You need to convert the values to Number, there are plenty of ways to do it:

var test1 = +window.prompt("Number1"); // unary plus operator
var test2 = Number(window.prompt("Number2")); // Number constructor
var test3 = parseInt(window.prompt("Number3"), 10); // an integer? parseInt
var test4 = parseFloat(window.prompt("Number4")); // parseFloat
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • Note: To know the differences between the unary plus operator, the `Number` constructor called as a function and `parseInt`/`parseFloat` check [this answer](http://stackoverflow.com/questions/4090518/string-to-int-use-parseint-or-number/4090577#4090577) – Christian C. Salvadó Nov 23 '10 at 23:50
  • Note 2: Using *no-op* mathematical operations such as `foo * 1;` or `foo - 0` are slightly equivalent to use the unary plus operator or the `Number` constructor called as a function. – Christian C. Salvadó Nov 23 '10 at 23:55
0
answer = parseInt(temp) + parseInt(temp2);

is what you're looking for

More information on parseInt: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Jason Benson
  • 3,371
  • 1
  • 19
  • 21
  • 1
    Please, don't link to w3schools, that's is by far the worse place one can go to. Link to MDC instead: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt – Ivo Wetzel Nov 23 '10 at 23:42
0

You need to explicitly convert them to numbers:

var answer = Number(temp) + Number(temp2);

A somewhat faster alternative is:

var answer = (temp - 0) + (temp2 - 0);
casablanca
  • 69,683
  • 7
  • 133
  • 150
0

by default, text from window.prompt is interpreted as string so the + operator concatinates them, you need to parse the values to integers using parseInt

Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
0

The problem is that your input is a string (text) and you have to convert it to a number.

You can do that with the parseInt() function or by mixing it with another number.

Examples:

var temp = window.prompt("Number1") * 1;
var temp = parseInt(window.prompt("Number2");
Wolph
  • 78,177
  • 11
  • 137
  • 148