Using bitwise OR 0 to floor a number

前端 未结 6 1827
抹茶落季
抹茶落季 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:52

    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.

提交回复
热议问题