最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Input Numbers - Stack Overflow

programmeradmin2浏览0评论

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 user258875user258875
Add a ment  | 

5 Answers 5

Reset to default 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
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");
发布评论

评论列表(0)

  1. 暂无评论