Rounding numbers down

JavaScript performance comparison

Revision 4 of this test case created and last updated

Info

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 code

<script>
  var n = Math.PI, // 3.141592653589793
      substr = String.prototype.substr,
      split = String.prototype.split,
      indexOf = String.prototype.indexOf;
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Math.floor
Math.floor(n); // 3
pending…
parseInt
parseInt(n, 10); // 3
pending…
Double bitwise NOT
~~n; // 3
pending…
Bitwise OR
n | n; // 3
pending…
Bitwise OR with 0
n | 0; // 3
pending…
Bitwise AND
n & n; // 3
pending…
Bitwise left shift
n << 0; // 3
pending…
toString, split, and toNumber
('' + n).split('.')[0] * 1; // 3
pending…
String.prototype.substr and indexOf with conversion
+String.prototype.substr.call(n, 0, String.prototype.indexOf.call(n, '.', 0)); // 3
pending…
Cached String.prototype.substr
+substr.call(n, 0, indexOf.call(n, '.', 0)); // 3
pending…
String.prototype.split
+String.prototype.split.call(n, '.')[0]; // 3
pending…
Cached String.prototype.split
+split.call(n, '.')[0]; // 3
pending…
Bitwise right shift
n >> 0; // 3
pending…
Bitwise zero-fill right shift
n >>> 0; // 3
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment