Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Help!! Adding two number variables

    Im having truble with this code

    in alert(q+w) if q is 3, and w is 4 it will display 34 not 7
    and if e==false it still does if r==true

    help
    [code]
    var q=prompt("Type your first number");
    var w=prompt("Type your second number");
    var e=confirm("do you want to add the two numbers");
    if (e==true)
    {alert(q+w);
    }
    else if (e==false)
    {var r=confirm("do you want to subtract the two numbers");
    }
    if (r==true)
    {alert(q-w);}
    Last edited by daniel2489; 03-15-2009 at 05:41 PM. Reason: no replys

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,734
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Values in Javascript are interpreted as strings unless converted to numbers.
    So 2+5 = 25 when the two string values are concatenated, but 2+5 = 7 when transformed to numbers using parseInt(), parseFloat(), Number() or simply by *1.

    Try this:-

    Code:
    <script type = "text/javascript">
    
    var q = parseFloat(prompt("Type your first number",""))  || 0;  // default value 0
    var w = parseFloat(prompt("Type your second number",""))  || 0;  // default value 0
    var e = confirm("Do you want to add the two numbers");
    if (e) {
    alert("The two numbers added come to " + (q+w));
    }
    else {
    var r = confirm("Do you want to subtract the two numbers");
    }
    if (r) {
    alert("The two numbers subtracted come to " + (q-w));
    }
    if (r) is the equivalent of if r == true, and if(!r) is the equivalent of if r == false. But true/false is binary so not true = false and not false = true.

    Full marks for changing you thread title to something meaningful. By [code] tags, what is meant is use the # or octothorpe button on the toolbar - Wrap [CXDE] tags around the selected text - I have had to change CODE to CXDE as otherwise it will do just that!


    “The expert at anything was once a beginner”
    Last edited by Philip M; 03-15-2009 at 05:55 PM.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •