Format numbers with grouped thousands

Benchmark created by Mathias Bynens on


Description

Dmitry Baranovskiy blew my mind with his dirtyCommas function, in which a very clever regular expression is used to format numbers with grouped thousands. Let’s see how it compares to other solutions.

Note that the functions benchmarked here were designed for use with positive integers only.

Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
Old formatNumber
formatNumber1(100);
formatNumber1(1000);
formatNumber1(10000);
formatNumber1(100000);
formatNumber1(1000000);
formatNumber1(10000000);
formatNumber1(100000000);
ready
Dmitry’s clever regex
formatNumber2(100);
formatNumber2(1000);
formatNumber2(10000);
formatNumber2(100000);
formatNumber2(1000000);
formatNumber2(10000000);
formatNumber2(100000000);
ready

Revisions

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