Sunday, September 23, 2012

Format Number with a Thousand Separator

Here are a couple of helpful functions to work with number.
The first one formats a number with a thousand separator. A comma is used as a thousands separator.


function format(obj){
  var str = obj.toString();
  var re=/(-?\d+)(\d{3})/;
  while(re.test(str)){
   str=str.replace(re,'$1,$2')
  }
  return str;
}

This one removes formatting:
function deformat(str){
 var re = /,/g;
   return str.replace(re,'');
}