javascript calculation

Discussion in 'JavaScript' started by quad_design, Dec 3, 2008.

  1. #1
    Hi,

    Im having a problem with a javascript calculation i am trying to do.

    ----------------

    function Skirting()
    {
    var width = prompt("Please enter the total width of your room (meters):", "");
    var length = prompt("Please enter the total length of skirting (meters):","");
    var price = 2;
    return width + length * price ;

    ----------------

    For some reason when i enter width=2 length=2 i get the answer 24. All i want is a simple calculation of width + length * price = 8.

    Can anyone see the mistake, do you need to put a plus in brackets or something?

    Thank you for any help :)
     
    quad_design, Dec 3, 2008 IP
  2. agnus

    agnus Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    When you return the value, the actual thing that is happening is that your script concatenates the width value to the length value multiplied by price.
    To convert width to integer use Number(width)
    
    function Skirting()
    {
    var width = prompt("Please enter the total width of your room (meters):", "");
    var length = prompt("Please enter the total length of skirting (meters):","");
    var price = 2;
    return Number(width) + length * price ;
    
    Code (markup):
     
    agnus, Dec 3, 2008 IP
  3. quad_design

    quad_design Peon

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you for the quick reply agnus :)

    Still no luck its still messing up, any chance someone can have a look at this/....

    function Walls()
    {
    var width = prompt("Please enter the total width of your room (meters):", "");
    var length = prompt("Please enter the total length of skirting (meters):","");
    var price = 5;
    return Number(width) * 2 + length * price ;

    The javascript just dosnt to read it correctly for example it will use 3+4 =34

    It should be...

    width x2 + length x price
     
    quad_design, Dec 3, 2008 IP
  4. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You need to use parseInt since prompt() returns a string.
     
    MMJ, Dec 3, 2008 IP