Ramblings

October 1, 2008

Getting an int from math calculations in javascript

Filed under: cool, javascript, tip — michaelangela @ 6:02 am

Javascript – Casting to integer on arithmetic division… – Rexiology… – MSMVPS.COM

As Javascript been a weak-typed language, sometimes it’s not able to
cast a variable from one type to another. as in arithmetic division, if
one wants to output an integer instead of a double or else, here is a
way learned from this article that’s useful:

a = ( b / c ) | 0

by using a bitwise OR operation to cast a float / double
back to an integer, to have a way casting some numeric values back to
desired form.

As Javascript been a weak-typed language, sometimes it’s not able to cast a variable from one type to another. as in arithmetic division, if one wants to output an integer instead of a double or else, here is a way learned from this article that’s useful:

a = ( b / c ) | 0

by using a bitwise OR operation to cast a float / double back to an integer, to have a way casting some numeric values back to desired form.

Advertisements

1 Comment »

  1. although it does not work sometimes, but most the time, it works magically.

    great info…

    Comment by khaled khunaifer — November 28, 2010 @ 5:48 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

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

Create a free website or blog at WordPress.com.

%d bloggers like this: