develop

Simple javascript format currency function

A handy little format currency function

Wrote this recently after finding an answer by Tim Pietzcker at stackoverflow.com. Thought it was quite neat.

Credit: Jeffrey Friedl, [Mastering Regular Expressions, 3rd. edition][oreilly], p. 66-67 [oreilly]: http://oreilly.com/catalog/9780596528126/

/*****************
 * 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)(?=(\d\d\d)+(?!\d))/g, "$1" + sep) + (n.length > 1 ? decChar + n[1].substr(0,dec) : '') + (post || '');
}