Forum Moderators: open

Message Too Old, No Replies

adding variables (from strings to numbers)

         

EfremJ

1:48 am on Sep 20, 2009 (gmt 0)

10+ Year Member



I know I'm probably missing something really simple but I cannot for the life of me get this code to work:

// variables section
var firstNumber;
var secondNumber;
var outputNumber;

// input section
firstNumber = prompt("Enter a number:");
secondNumber = prompt("Enter a second number:");

// processing section
outputSum = firstNumber + secondNumber;

//output section
document.write(outputNumber);

When I am prompted to input a number, I type in 15. When I am prompted for the second number I type 10.

I want them to add up to 25 but they keep adding as strings and producing "1510".

What am I missing..?

Fotiman

2:39 am on Sep 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld! In JavaScript, the + operator also acts as the string concatenation operator. What you need to do is force your variables to be interpreted as numbers. One way you could do this is using the parseInt and parseFloat functions. For example:

outputSum = parseInt(firstNumber, 10) + parseInt(secondNumber, 10);

Hope that helps. :)

EfremJ

3:39 am on Sep 20, 2009 (gmt 0)

10+ Year Member



Hi, Fotiman.

I'll give that a try and see how it works. Thanks for the response!

EfremJ

3:43 am on Sep 20, 2009 (gmt 0)

10+ Year Member



That worked like a charm! Thanks so much for the assistance!

rocknbil

3:42 pm on Sep 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For posterity's sake, it sometimes gets worse when you try to add decimal numbers [webmasterworld.com].

EfremJ

6:53 pm on Sep 20, 2009 (gmt 0)

10+ Year Member



rocknbil--thanks for the reference. I'll definitely make a note of it for posterity. For the present, the challenge is based on whole numbers, so that's a bit of a relief for me!