Number formatting with commas

JavaScript performance comparison

Test case created by Prashant

Info

to check the performance of regex over a native method Number.toLocaleString() and an array based implementation for number formatting in JavaScript.

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
without regex
function formatNumber(num) {
  var decimalPart = '';
  num = num.toString();
  if (num.indexOf('.') != -1) {
    decimalPart = '.' + num.split('.')[1];
    num = parseInt(num.split('.')[0]);
  }
  var array = num.toString().split('');
  var index = -3;
  while (array.length + index > 0) {
    array.splice(index, 0, ',');
    index -= 4;
  }
  return array.join('') + decimalPart;
};
formatNumber(4343535353.53);
pending…
with regex
function formatNumberRgx(num) {
  var parts = num.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
};
formatNumberRgx(4343535353.53);
pending…
with locale string
var number = 4343535353.53;
number.toLocaleString();
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

Damith Thamara commented :

Great work. Thanks

Add a comment