Flooring numbers in JavaScript: ~~n, n|0 or Math.floor(n)?

与世无争的帅哥 提交于 2019-12-22 09:37:03

问题


I've recently discovered some other ways to remove the fractional part of numeric values in JavaScript other than Math.floor(n), specifically the double bitwise NOT operator ~~n and performing a bitwise or with 0 n|0.

I'd like to know what are the difference between these approaches and what the different scenarios are where one method is recommended over another.


回答1:


Be clear to the next person looking at your code and use Math.floor().

The performance gain of 1%-40% isn't really worth it, so don't make your code confusing and hard to maintain.




回答2:


The operands of all bitwise operators are converted to signed 32-bit integers:

Math.floor(2147483648) // 2147483648
2147483648 | 0         // 2147483648
~~2147483648           // 2147483648

Math.floor(2147483649) // 2147483649
2147483649 | 0         // -2147483647
~~2147483649           // -2147483647

So use Math.floor();




回答3:


(I entirely agree with josh's answer: favor clear maintainable code.)

Here is an explanation on the other bit-wise approaches:

The bit-wise operators work because they only operator on 32-bit (signed) integers but numbers in JavaScript are all IEEE-754 values. Thus, there is an internal conversion (truncation, not floor!) that happens to operands for bit-wise operators.

The applied bit-wise operation (e.g. n<<0, ~~n or n|0) then acts as an identity function which "does nothing" to the converted values: that is, all of these approaches rely on the same conversion applied to bit-wise operands.

Try n as a negative number or a value outside of [-231, 231-1]:

(-1.23|0)            // -1
Math.floor(-1.23)    // -2

var x = Math.pow(2, 40) + .5
x|0                  // 0
Math.floor(x)        // 1099511627776

Happy coding.



来源:https://stackoverflow.com/questions/10890486/flooring-numbers-in-javascript-n-n0-or-math-floorn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!