开发者

Javascript Input Numbers

开发者 https://www.devze.com 2023-01-27 04:19 出处:网络
How do you take 2 numbers from the User with window.prompt and add them up without concatenating? What I thought was:

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 o开发者_运维技巧nly concatenates not adds.


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


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


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);


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


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消