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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With