Very basic question

Discussion in 'JavaScript' started by TOSCS, Mar 22, 2011.

  1. #1
    I want to take three values in from the user and perform various basic mathematical operations on them.

    I am taking input like this:
    var firstnumber = prompt("blah blah...
    var secondnumber = prompt("blah blah...

    and then adding them together like this
    var result = firstnumber+secondnumber

    However this just concatenates the values as if they were strings, e.g. if you entered "7" and "3" instead of getting 10 you get 73!

    I know how to add them if I hard-coded the variables, but I want the user to input them.
     
    TOSCS, Mar 22, 2011 IP
  2. Jan Novak

    Jan Novak Peon

    Messages:
    121
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    0
    #2
    You can use parseInt or parseFloat functions to do it.

    var result = parseInt(firstnumber)+parseInt(secondnumber)
     
    Jan Novak, Mar 22, 2011 IP
  3. AltIvan

    AltIvan Peon

    Messages:
    76
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    just use "Number()"; this way:

    var result = Number(firstnumber)+Number(secondnumber)
    
    Code (markup):
     
    AltIvan, Mar 22, 2011 IP