Wednesday, January 6, 2010

How do you add two numbers rather than concatenate them in Javascript?

var x = prompt(';Add two numbers...';, ';Number 1';);


var y = prompt(';Add two numbers...';, ';Number 2';);


document.write(x + '; + '; + y + '; = '; + (x + y));





This outputs ';11'; if you input 1 and 1 for x and y. How do you get it to output ';2';?How do you add two numbers rather than concatenate them in Javascript?
%26lt;script type=';text/javascript';%26gt;


var x = prompt(';Add two numbers...';, ';Number 1';)*1;


var y = prompt(';Add two numbers...';, ';Number 2';)*1;


var Z = x + y


document.write(Z);


%26lt;/script%26gt;How do you add two numbers rather than concatenate them in Javascript?
Cast individually x and y into numbers, they came into x and y as ';1'; and ';1'; you want to reprocess them into 1 and 1.

No comments:

Post a Comment