Number formatting with commas

JavaScript performance comparison

Revision 10 of this test case created by

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
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(156.29);
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(156.29);
pending…
with locale string
var number = 156.29;
number.toLocaleString();
pending…
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(156.29, 2);
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