Posts Tagged ‘Number Formatting’

When presenting a number to the UI, often it is needed in a formatted form. This function extends the number object in JavaScript to provide this functionality.

Usage:

var x = 10000;

var xString = x.toGroupingString(2);
// xString is now: 10, 000.00
// Adds in number grouping and precision
Number.prototype.toGroupingString = function (precision) {
  var nStr = this.toFixed(precision) + '';
  x = nStr.split('.');
  x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
  return x1 + x2;
};

We can add to this to allow presenting ratios as percentages.

// Formats a ration (0.5) as a percent (50%)
Number.prototype.toPercentString = function (precision) {
  var num = this * 100;
  return num.toGroupingString(precision) + '%';
};