Using bitwise OR 0 to floor a number

A colleague of mine stumbled upon a method to floor float numbers using a bitwise or:

var a = 13.6 | 0; //a == 13

We were talking about it and wondering a few things.

  • How does it work? Our theory was that using such an operator casts the number to an integer, thus removing the fractional part
  • Does it have any advantages over doing Math.floor ? Maybe it's a bit faster? (pun not intended)
  • Does it have any disadvantages? Maybe it doesn't work in some cases? Clarity is an obvious one, since we had to figure it out, and well, I'm writting this question.
  • Thanks.


    How does it work? Our theory was that using such an operator casts the number to an integer, thus removing the fractional part

    All bitwise operations except unsigned right shift, >>> , work on signed 32-bit integers. So using bitwise operations will convert a float to an integer.

    Does it have any advantages over doing Math.floor? Maybe it's a bit faster? (pun not intended)

    http://jsperf.com/or-vs-floor/2 seems slightly faster

    Does it have any disadvantages? Maybe it doesn't work in some cases? Clarity is an obvious one, since we had to figure it out, and well, I'm writting this question.

  • Will not pass jsLint.
  • 32-bit signed integers only
  • Odd Comparative behavior: Math.floor(NaN) === NaN , while (NaN | 0) === 0

  • This is truncation as opposed to flooring. Howard's answer is sort of correct; But I would add that Math.floor does exactly what it is supposed to with respect to negative numbers. Mathematically, that is what a floor is.

    In the case you described above, the programmer was more interested in truncation or chopping the decimal completely off. Although, the syntax they used sort of obscures the fact that they are converting the float to an int.


    Your first point is correct. The number is cast to an integer and thus any decimal digits are removed. Please note, that Math.floor rounds to the next integer towards minus infinity and thus gives a different result when applied to negative numbers.

    链接地址: http://www.djcxy.com/p/2170.html

    上一篇: 如何在JavaScript中获取当前日期?

    下一篇: 使用按位或0来放置一个数字