PDA

View Full Version : Help!! Adding two number variables

daniel2489
03-15-2009, 05: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 e=confirm("do you want to add the two numbers");
if (e==true)
}
else if (e==false)
{var r=confirm("do you want to subtract the two numbers");
}
if (r==true)

Philip M
03-15-2009, 05: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) {
}
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”