Number formatting with commas (v9)

Revision 9 of this benchmark created on


Description

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

Test runner

Ready to run.

Testing in
TestOps/sec
without regex
function formatNumber(num) {
  var array = num.toString().split('');
  var index = -3;
  while (array.length + index > 0) {
    array.splice(index, 0, ',');
    index -= 4;
  }
  return array.join('')
};
formatNumber(23665);
ready
with regex
function formatNumberRgx(num) {
  var parts = num.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
};
formatNumberRgx(23665);
ready
with locale string
var number = 23665;
number.toLocaleString();
ready
numberFormat
function numberFormat(number, decimals) {
  if (typeof number === "string") {
    number = parseFloat(number);
  }
  if (isNaN(number) || (number == 0)) {
    if (decimals === 0)
      return "0";
    else
      return "0,0000000000".substring(0, decimals + 2)
  }
  var sign = "";
  if (number < 0) {
    number = -number;
    sign = "-";
  }
  var parts = (number.toFixed(decimals)).split("."),
    s = parts[0],
    i = s.length,
    L = i,
    o = "";
  while (i--) {
    o = (i == 0 ? "" : ((L - i) % 3 ? "" : ".")) + s.charAt(i) + o;
  }
  if (decimals === 0)
    return sign + o;
  return sign + o + "," + parts[1];
}

numberFormat(23665, 0);
ready

Revisions

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