Format Number with Thousand markers

Format Number with Thousand markers

by Keyur Patel

JavaScript

var billion = 1000000000000000000;

function formatThousands(n, dp) {
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.' + Math.round(d * Math.pow(10,dp||2)) : '');
}

alert(formatThousands(billion));

/// http://jsperf.com/compare-two-format-thousands