Return to Snippet

Revision: 17478
at September 6, 2009 21:22 by enchance


Initial Code
function formatNumber(num, prefix){
   prefix = prefix || '';
   num += '';
   var splitStr = num.split('.');
   var splitLeft = splitStr[0];
   var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
   var regx = /(\d+)(\d{3})/;
   while (regx.test(splitLeft)) {
      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + splitLeft + splitRight;
}

function unformatNumber(num) {
   return num.replace(/([^0-9\.\-])/g,'')*1;
}


//Usage:
var test1 = formatNumber('5123456789.25'); // returns 5,123,456,789.25
var test2 = formatNumber(1234.15,'$');     // returns $1,234.15
var test3 = unformatNumber('$1,234.15');   // returns 1234.15

Initial URL

                                

Initial Description

                                

Initial Title
Format numbers w/ commas

Initial Tags

                                

Initial Language
JavaScript