Javascript Input Numbers
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
Solution 1:
You need to convert the values to Number, there are plenty of ways to do it:
var test1 = +window.prompt("Number1"); // unary plus operatorvar test2 = Number(window.prompt("Number2")); // Number constructorvar test3 = parseInt(window.prompt("Number3"), 10); // an integer? parseIntvar test4 = parseFloat(window.prompt("Number4")); // parseFloat
Solution 2:
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
Solution 3:
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);
Solution 4:
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
Solution 5:
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");
Post a Comment for "Javascript Input Numbers"