admin管理员组文章数量:1430953
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.
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.
Share Improve this question asked Nov 23, 2010 at 23:39 user258875user2588755 Answers
Reset to default 8You 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/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");
本文标签: Javascript Input NumbersStack Overflow
版权声明:本文标题:Javascript Input Numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745557455a2663269.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论