Zhongde Liu

This is my personal "Clipboard" of web development stuff I come across


Leave a comment

Code: “cast a number to int” with bitwise operators

In order to cast a number to an int value you can also use bit operations. In particular the Double NOT and the OR 0.

~~(3.14) // => 3
3.14 | 0 // => 3

As these operations are working on on signed 32-bit integers per default, the number is in fact truncated after the comma. This also works on negative numbers.

~~(-3.14) // => -3
-3.14 | 0 // => -3

You are asking Why? Why should anyone bother bitwise operators? one word: Performace. If you are crunching a lot, I mean, a lot, numbers, you should notice something. I made a quick jsperf http://jsperf.com/parseint-and-bitwise-operations. You see the bit operations are more thanĀ 10x faster than parseInt.

Sidenote: Math.floor is also pretty fast. However Math.floor results in a different result number when used with negative ones.

Math.floor(-3.14) // => -4