Wrote this recently after finding an answer by Tim Pietzcker at [stackoverflow.com][stackoverflow]. Thought it was quite neat. [stackoverflow]: http://stackoverflow.com/questions/2254185/regular-expression-for-formatting-numbers-in-javascript Credit: Jeffrey Friedl, [Mastering Regular Expressions, 3rd. edition][oreilly], p. 66-67 [oreilly]:http://oreilly.com/catalog/9780596528126/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/***************** * formats number into currency * * num : the value to be formatted * dec : the number of decimals to be returned * sep : the thousands seperator * decChar : the decimals seperator * pre : string to prefix the result * post : string to postfix the result **/ function formatCurrency(num,dec,sep,decChar,pre,post) { var n = num.toString().split(decChar); return (pre || '') + n[0].replace(/(d)(?=(ddd)+(?!d))/g, "$1" + sep) + (n.length > 1 ? decChar + n[1].substr(0,dec) : '') + (post || ''); } |