...

# Help!! Adding two number variables

daniel2489
03-15-2009, 06:30 PM
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);}

Philip M
03-15-2009, 06:45 PM
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:-

<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”

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum