Format numbers with grouped thousands

JavaScript performance comparison

Revision 2 of this test case created

Info

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 code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<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>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
100
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. Here’s a list of current revisions for this page:

1 comment

Juan Carlos commented :

It doesnt work with numbers higher than 99,999,999

Add a comment