Using bitwise OR 0 to floor a number

前端 未结 6 1747
抹茶落季
抹茶落季 2020-11-22 05:01

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

6条回答
  •  伪装坚强ぢ
    2020-11-22 05:49

    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.

提交回复
热议问题