Search code examples
javascriptarea

Javascript Trapezoid area calculation with user input, incorrect result


I am trying to make a javascript program that calculates the area of a trapezoid. So far below is my js code:

var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
    var tr1=prompt("Enter the top base.")
    var tr2=prompt("Enter the bottom base.")
    var tr3=prompt("Now enter the height.")
    confirm((tr1+tr2)*(tr3)/2)
}

But when I put 4,5,6 in my calculator, it spits out 135 instead of 27.

Why?


Solution

  • You can use parseInt to set the values as integers.

    var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
    if(lol==="trapezoid"){
        var tr1=Number(prompt("Enter the top base."))
        var tr2=Number(prompt("Enter the bottom base."))
        var tr3=Number(prompt("Now enter the height."))
        confirm((tr1+tr2)*(tr3)/2)
    }
    

    Here's a JSFiddle with Benjamine's Number point

    http://jsfiddle.net/cXWnk/