Forum Moderators: open

Message Too Old, No Replies

adding/subtracting numbers and variables problem, (newbie)

numbers and variables problem

         

andre73

10:23 pm on Nov 1, 2004 (gmt 0)

10+ Year Member



I am trying to subtract the value in the variable dob from 2004, it works fine if I remove the text "you are" and the +sign but as it is here i get NaN, can anyone tell me how I should do to display You are, "the value of 2004-dob)

<html>
<body>
<script language="javascript" type="text/javascript">
var greetingString = "Hello "
var name = prompt("What is your name","Enter your name here please");
var dob = prompt("When were you born","please enter the year here");

document.write(greetingString + " " + name + "<BR/>");
document.write("you are" + 2004 - dob);
</script>
</body>
</html>

Lance

11:06 pm on Nov 1, 2004 (gmt 0)

10+ Year Member



Try adding (parentheses) like so:

document.write("you are" + (2004 - dob));

Do the math first, then build the string.

andre73

11:11 pm on Nov 1, 2004 (gmt 0)

10+ Year Member



thanks!

Bernard Marx

11:23 pm on Nov 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Reason:

"you are" + 2004 --> "you are2004"

and

"you are2004" - dob --> NaN (not a number)

StupidScript

11:31 pm on Nov 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Mr. Marx,

The other day I had to explicity declare values as Number()s.

a=200;
b=50;
thisNumber = a + b;

returned

20050

so I ended up using (successfully)

a=200;
b=50;
thisNumber = Number(a) + Number(b);

I hadn't had to do that, years ago when the first example would suffice. How is andre73's situation different? I know he's concatenating a string plus the result of subtracting two numbers, but I don't see the Number() function being used.