Number formatting with commas

JavaScript performance comparison

Revision 17 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var number = 4343005353.53;
  
  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;
  };
  
  function formatNumberRgx(num) {
    var parts = num.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
  };
  
  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) {
        for (var i = remainder.length; i < 3; i++) {
          remainder = "0" + remainder;
        }
      }
      formatted = remainder + formatted;
    }
    if (absValue !== floorValue) {
      formatted += "." + original.toString().split('.')[1];
    }
    if (isNegative) {
      formatted = "-" + formatted;
    }
    return formatted;
  }

};
</script>

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
formatNumber(number);
pending…
with regex
formatNumberRgx(number);
pending…
with locale string
number.toLocaleString();
pending…
using remainders
formatWithRemainders(number);
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