Adding Numbers Correctly with Javascript using parseInt()

April 25th, 2010 - Posted by Steve Marks to Javascript / jQuery, Web Development.

Are you adding 2 and 2 together and getting 22? It’s a common problem with adding numbers, especially if the numbers are being passed via a user’s input in a textfield.

The problem here is that the numbers are being treated as strings and doing something like below will result in the incorrect result being output:

var number_one_to_add = document.form1.number_one.value;
var number_two_to_add = document.form1.number_two.value;
alert(number_one_to_add + number_two_to_add);

So how do we get round this? Well, all that needs to happen is to tell Javascript to treat our numbers as integers rather than strings. We do this via the parseInt() function. As a result our updated code should now look like so:

var number_one_to_add = parseInt(document.form1.number_one.value);
var number_two_to_add = parseInt(document.form1.number_two.value);
alert(number_one_to_add + number_two_to_add);

In doing this we now get the correct answer.

This entry was posted on Sunday, April 25th, 2010 at 9:10 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments (0)
Comments are closed.