Number formatting with commas (v14)

Revision 14 of this benchmark created by Maros 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 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(4343005353.53);
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(4343005353.53);
ready
with locale string
var number = 4343005353.53;
number.toLocaleString();
ready
using remainders
function formatWithRemainders(value) {
  var original = value;
  var isNegative = value < 0;
  var absValue = Math.abs(value);
  var floorValue = Math.floor(absValue);
  var v = floorValue;
  if (v == 0) return "0";
  var formatted = "";
  while (v > 0) {
    if (formatted.length > 0) {
      formatted = "," + formatted;
    }
    var remainder = (v % 1000);
    v = Math.floor(v / 1000);
    if (v > 0) {
      if (remainder < 10) {
        remainder = "00" + remainder;
      } else if (remainder < 100) {
        remainder = "0" + remainder;
      }
    }
    formatted = remainder + formatted;
  }
  if (absValue !== floorValue) {
    formatted += "." + original.toString().split('.')[1];
  }
  if (isNegative) {
    formatted = "-" + formatted;
  }
  return formatted;
}
formatWithRemainders(4343005353.53);
ready
Add commas
function addCommas(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }
addCommas(4343005353.53);
ready

Revisions

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