Add Commas To Numbers

From GreaseSpot

Jump to: navigation, search

Numbers look more readable with commas. The following function will add them to every integer in a string.

function commafy(num) {
  var str = (num+"").split("."),
  dec=str[1]||"",
  num=str[0].replace(/(\d)(?=(\d{3})+\b)/g,"$1,");
  return (dec) ? num+'.'+dec : num;
}

Example usage:

commafy("123456789.12345");
//gives: "123,456,789.12345"
Personal tools