Welcome to WebmasterWorld Guest from

Forum Moderators: open

Adding jscript variables as numbers, not text strings

11:58 am on Apr 9, 2003 (gmt 0)

10+ Year Member

Hello all. How can I add two variables, both of which are integers, without it adding them together as text strings?
For example.

function add() {
var number1=box1.value;
var number2=box2.value;
var number3=Math.abs(number1+number2);
box3.value=number3; }

If box1.value is "2" and box2.value is "3" it box3.value should come out as "5" but instead it comes out as "23".

12:04 pm on Apr 9, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

for integers
parseInt(number1,10) + parseInt(number2,10)

for floats/decimals
parseFloat(number1) + parseFloat(number2)

If you're wondering what the second parameter (10) in parseInt is for:

radix [ - the second parameter]
Optional. A value between 2 and 36 indicating the base of the number contained in [the first parameter]. If not supplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' are considered octal. All other strings are considered decimal.

- from MicroSoft's JScript documentation

So if you put the string "09" into parseInt without specifying base10 as the radix you'll end up with an octal integer.... I had some crazy fun with this once when I didn't have a monkeys what was going on!

12:07 pm on Apr 9, 2003 (gmt 0)

10+ Year Member

Great! It's working now. Thanks.
1:02 pm on Apr 9, 2003 (gmt 0)

10+ Year Member

Just to add a quick tip,

Minusing zero from a varable will force JavaScript to interpret as a number.

so, in the above case

var number1=box1.value -0;

will change the type of number1 from a string to the numeric value.


Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month