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.

7 Answers
7

Leave a Comment