Currency

Convert number to currency format with optional thousands separator and specifiable currency sign and decimal places.

by Hans PUFAL

JavaScript

// Recommend use of Object.implement : http://jsfiddle.net/jstoolsmith/nyeeB/
// Number.implement (function currency (c, curr, sep) {...});

Number.prototype.currency = function (c, curr, sep) {
    var n = this;
    curr = (curr || (curr === '' ? '' : '$')).match(/^(\>)?(.+)$/) || ['', '', '$'];
    curr = curr[1] ? ['', curr[2]] : [curr[2], ''];

    !sep && sep !== '' && (sep = ',');
    c = n.toFixed(arguments.length === 0 ? 2 : c).split('.');
    n = [c[1] && (sep === '.' ? ',' : '.'), c[1]];
    c = c[0];
    while (c.length > 3) {
        n.unshift(sep, c.slice(-3));
        c = c.slice(0, -3);
    }
    return curr[0] + c + n.join('') + curr[1];
};

// Minified (336 characters) http://jsfiddle.net/jstoolsmith/XdJWH/
// Number.prototype.currency=function(e,b,a){var d=this;b=(b||(b===""?"":"$")).match(/^(\>)?(.+)$/)||["","","$"];b=b[1]?["",b[2]]:[b[2],""];!a&&a!==""&&(a=",");e=d.toFixed(arguments.length===0?2:e).split(".");d=[e[1]&&(a==="."?",":"."),e[1]];e=e[0];while(e.length>3){d.unshift(a,e.slice(-3));e=e.slice(0,-3)}return b[0]+e+d.join("")+b[1]};

document.write((5123456.90).currency(2, '> EUR', ',') + '</br>');
document.write((23456.1234).currency(2, '$', ' ') + '</br>');
document.write((3456.99).currency(2, 'EUR ', '.') + '</br>');
document.write((1456.999).currency(2, '> USD', ' ') + '</br>');
document.write((56).currency(2, 'EUR ', '.') + '</br>');
document.write((6).currency() + '</br>');