homepage Welcome to WebmasterWorld Guest from 54.161.202.234
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Adding jscript variables as numbers, not text strings
McIntyre




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

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".

 

joshie76




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

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!

McIntyre




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

Great! It's working now. Thanks.

HocusPocus




msg:1488980
 1:02 pm on Apr 9, 2003 (gmt 0)

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved