Javascript Money Format a Number

I’m constantly needing to format a number as currency for display in the UI.
Here’s a little prototype I whipped up to facilitate this. Currently it’s only working for US format, but should be pretty simple to modify. Please consider letting me know if you do modify it.

	/**
	 * formatMoney
	 * @param  {Numeric} len Length of decimals
	 * @param  {String}  sep Thousands seperator
	 * @param  {String}  dec Decimal seperator
	 * @param  {String}  sym Money symble
	 * @return {String}
	 */
	Number.prototype.formatMoney = function (len, sep, dec, sym)
	{
		// this number
		var num = this;

		// setup defaults
		len = (typeof len === 'undefined') ?  2  : len;
		sep = (typeof sep === 'undefined') ? ',' : sep;
		dec = (typeof dec === 'undefined') ? '.' : dec;
		sym = (typeof sym === 'undefined') ? '$' : sym;

		// Start formating
		// round up decimal to len specified
		num = num.toFixed( len ).toString();
		// add thousands seperator every third diget
		num = sym + num.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,'$1'+ sep);

		return num;
	};

And here it is minified:

Number.prototype.formatMoney=function(a,b,c,d){var e=this;return a=typeof a=="undefined"?2:a,b=typeof b=="undefined"?",":b,c=typeof c=="undefined"?".":c,d=typeof d=="undefined"?"$":d,e=e.toFixed(a).toString(),e=d+e.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+b),e}

Leave a Reply

Your email address will not be published. Required fields are marked *