decimal rounding toFixed vs Math.round (v50)

Revision 50 of this benchmark created by Gust van de Wal on


Setup

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)

Test runner

Ready to run.

Testing in
TestOps/sec
toFixed 1
number.toFixed(1)
ready
Function 2 A
fixToTwoA(number)
ready
Function 1 A
fixToOneA(number)
ready
Function 1 B
fixToOneB(number)
ready
Function 2 B
fixToTwoB(number)
ready
toFixed 2
number.toFixed(2)
ready

Revisions

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

  • Revision 1: published on
  • Revision 2: published on
  • Revision 3: published on
  • Revision 4: published on
  • Revision 5: published on
  • Revision 6: published on
  • Revision 7: published on
  • Revision 8: published on
  • Revision 9: published by Julian Diaz on
  • Revision 10: published on
  • Revision 16: published on
  • Revision 23: published by TJKoury on
  • Revision 27: published by Yanislav Igonin on
  • Revision 31: published by Stephen Irving on
  • Revision 32: published by Stephen Irving on
  • Revision 34: published by Stephen Irving on
  • Revision 45: published by Stephen Irving on
  • Revision 46: published by Stephen Irving on
  • Revision 50: published by Gust van de Wal on
  • Revision 51: published by Kesavamoorthi Subramanian on
  • Revision 52: published by Kesavamoorthi Subramanian on
  • Revision 53: published by Kesavamoorthi Subramanian on
  • Revision 54: published by Kesavamoorthi Subramanian on
  • Revision 55: published by Kesavamoorthi Subramanian on