decimal rounding toFixed vs Math.round

JavaScript performance comparison

Revision 46 of this test case created by Stephen Irving

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var number = Math.random() * 100;

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Fix to One Place - Custom (ES5)
var fixToOne = function (num) {
  return (num = Math.round(num * 10) / 10) + (num === (num|0) ? '.0' : '');
};
fixToOne(number);
pending…
Fix to One Place - toFixed(1)
number.toFixed(1);
pending…
Fix to One Place - Custom
const fixToOne = num =>
  (num = Math.round(num * 10) / 10) + (num === (num|0) ? '.0' : '');
fixToOne(number);
pending…
Fix to Two Places - Custom
const fixToTwo = num => (num = (Math.round(num * 100) / 100) +
  (num === (num|0) ? '.0' : 0)) + (num === (num|0) ? '.0' : '') +
  (num * 10 === ((num * 10)|0) ? '0' : '');
fixToTwo(number);
pending…
Fixed to Two Places - toFixed(2)
number.toFixed(2);
pending…
Fixed to Two Places - Custom (ES5)
var fixToTwo = function (num) {
  return (num = (Math.round(num * 100) / 100) +
    (num === (num|0) ? '.0' : 0)) + (num === (num|0) ? '.0' : '') +
    (num * 10 === ((num * 10)|0) ? '0' : '');
};
fixToTwo(number);
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.

0 Comments