casting to integers in JavaScript

I’ve been messing a little with some JavaScript fiddly bits last night and today, and I was caught out for a bit by need to cast a value to an int once divided. In Java it’s easy:

val = Integer.parseInt(numberA / numberB);

however, JavaScript isn’t that nice. Actually, once I solved it, I found JavaScript was even nicer!! By using a bitwise OR operation to cast a float/double back to an int like so:

val = (numberA / numberB) | 0;

Voila! It is cast from a float/double to an int.

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: