This question already has an answer here:
- Sum of two numbers with prompt 8 answers
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.
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