/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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