decimal rounding toFixed vs Math.round

JavaScript performance comparison

Revision 50 of this test case created by Gust van de Wal

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const number = Math.random() * 1000
  
  
  const fixToOneA = num => (num = ((num * 10)|0) / 10) + (num === (num|0) ? '.0' : '')
  const fixToTwoA = num => 
    (num = (((num * 100)|0) / 100) +
    (num === (num|0) ? '.0' : 0)) + (num === (num|0) ? '.0' : '') +
    (num * 10 === ((num * 10)|0) ? '0' : '')
  
  const fixToOneB = num => ~~num + '.' + ~~((num *= 10) % 10)
  const fixToTwoB = num => ~~num + '.' + ~~((num *= 10) % 10) + ~~((num *= 10) % 10)

};
</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
toFixed 1
number.toFixed(1)
pending…
Function 2 A
fixToTwoA(number)
pending…
Function 1 A
fixToOneA(number)
pending…
Function 1 B
fixToOneB(number)
pending…
Function 2 B
fixToTwoB(number)
pending…
toFixed 2
number.toFixed(2)
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