Rounding numbers down (v5)

Revision 5 of this benchmark created by Jordan on


Description

Note that some of the listed alternatives to Math.floor() use bitwise operators, which convert numbers to a 32-bit sequence.

These alternatives will only work with positive signed 32-bit floats, i.e. numbers from 0 to +2,147,483,647 (2^31-1).

~~2147483647.1; // 2147483647
~~2147483648.1; // -2147483648

Preparation HTML

<script>
  var n = Math.PI,
       // 3.141592653589793
      floorNew = (function() {
    var f = Math.floor,
        cap = 2 ^ 31;
    return function(n) {
     return n >= 0 && n < cap ? ~~n : f(n);
    }
   })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Math.floor
Math.floor(n); // 3
ready
parseInt
parseInt(n, 10); // 3
ready
Double bitwise NOT
~~n; // 3
ready
Bitwise OR
n | n; // 3
ready
Bitwise OR with 0
n | 0; // 3
ready
Bitwise AND
n & n; // 3
ready
Bitwise left shift
n << 0; // 3
ready
Math.floor + ~~n
floorNew(n)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.