Number formatting with commas

JavaScript performance comparison

Revision 8 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 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…
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(4343535353.53, 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