How do I sum numbers using a prompt, like a simple calculator? [duplicate]

丶灬走出姿态 提交于 2019-12-02 18:32:54

问题


I tried to do a REALLY simple thing using JavaScript, a percentage calculator. This is the code:

var num = prompt("What is the number?")
var perc = prompt("What is the percentage of change?")
var math = num / (perc + 100) * 100
var result = alert(eval(math))

But, for some reason, I can sum, for example:

var num1 = 15
var num2 = 100
alert(num1 + num2)

It will display 115, but I can't sum using something like this:

var num1 = prompt("Input a number.")
var num2 = 100
alert(num1 + num2)

If I write 15 in num1, the alert will display 15100. I tried some things, but none of them worked, so I really need help on this.


回答1:


Yours doesn't work because it's effectively doing "15" + 100 = 15100 because prompt returns a string.

You need to cast it from a string to a number using parseInt

var num1 = parseInt(prompt("Input a number."), 10) //10 for decimal
var num2 = 100
alert(num1 + num2)


来源:https://stackoverflow.com/questions/28482935/how-do-i-sum-numbers-using-a-prompt-like-a-simple-calculator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!