Format numbers with grouped thousands

JavaScript performance comparison

Test case created by Mathias Bynens

Preparation code

<script>
  function formatNumber1(number) {
   var comma = ',',
       string = Math.max(0, number).toFixed(0),
       length = string.length,
       end = /^\d{4,}$/.test(string) ? length % 3 : 0;
   return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
  }
  
  function formatNumber2(number) {
   return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
  }
</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
Old formatNumber
formatNumber1(100);
formatNumber1(1000);
formatNumber1(10000);
formatNumber1(100000);
formatNumber1(1000000);
formatNumber1(10000000);
formatNumber1(100000000);
pending…
Dmitry’s clever regex
formatNumber2(100);
formatNumber2(1000);
formatNumber2(10000);
formatNumber2(100000);
formatNumber2(1000000);
formatNumber2(10000000);
formatNumber2(100000000);
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