Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 742
Mick Byrne Avatar asked Dec 06 '22 14:12

Mick Byrne


2 Answers

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();

like image 200
jasssonpet Avatar answered Dec 27 '22 04:12

jasssonpet


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.

like image 40
josh3736 Avatar answered Dec 27 '22 04:12

josh3736