0

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.

Mr_Budo
  • 1
  • 1
  • 4
  • `prompt` returns a string, if you operate on a string with `+` you are doing concatenation. How is javascript supposed to know you want to treat those as numbers rather than strings? (Answer: you need to tell it to [parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) them). – Matt Burland Feb 12 '15 at 16:44

1 Answers1

4

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)
basher
  • 2,381
  • 1
  • 23
  • 34
  • Oh, thanks! But I don't understand that ", 10"... I removed it just to see what happened and the code still worked. – Mr_Budo Feb 12 '15 at 16:46
  • 1
    [The 10 is the radix and you should generally have it in place.](http://stackoverflow.com/questions/10398834/using-javascript-parseint-and-a-radix-parameter) 10 just means that you want to use decimals rather than hexidecimals (for example). – Andy Feb 12 '15 at 16:50