Rexiology::Work

Microsoft, Information Technologies...

Community

News

  • From Taiwan, living and working at Tokyo, Japan.

Recent Posts

Tags

Microsoft Sites

Other Sites

Blog pools

Bloggers

My other places

Archives

Site Info



Locations of visitors to this page




Logos & Chicklets


GeoURL


Rex's Certifications
Rex's Certifications


Creative Commons授權條款
本 著作 係採用
Creative Commons 授權條款



Javascript - Casting to integer on arithmetic division...

 

Been rushing on my working project and coding a lot Ajax using Ajax.net lately. Had a lot of  re-practice back to javascript. here is a quick pick of one of them.

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.

also there is a nice Javascript language reference I dig a lot during this coding. thanks for the help!

Technorati Tags: asp.net , programming , javascript 

 

Posted: 2006/1/9 13:12 by rextangtw | with 7 comment(s)
Filed under: ,

Comments

Jeffrey said:

I used to use another way:
a=parseInt(b/c)
the same result, maybe more readable.
For you ref.
# January 10, 2006 1:37 PM

rextangtw said:

Hey Jeffrey, thanks for the info. forgot to check out function list about this. but it's interesting that using a bit-wise OR can cast numbers back to integers, reminding myself back to the old days while coding x86 assembly language that only got bunch of cpu registers, haha.

Rex
# January 11, 2006 3:02 AM

Sander said:

Thanks for this tip! I'm new to JS and I expected array[array.length/2] to always return an element at least about in the middle. Not so. On un-even lengths it returns undefined. So I added your |0 and now it works great! Thanks also Jeffrey for the parseInt function. I agree it's more readable but it not as hackish :)

I use it to steer a Google Map to the middle of the path I'm displaying.
# January 25, 2007 11:39 AM

parke said:

Thank you...

# August 27, 2008 9:46 AM

barosl said:

It is a very interesting result. I have always used parseInt, but now I have another way to cast to integer!

# September 15, 2008 12:03 AM

Vasco Costa said:

You're my new god!

# January 14, 2009 7:45 PM