Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Format Currency //Javascript Function (See related posts)


Formats strings/numbers into "money format" without loops :)

Defaults:
float ploint cutoff = 2 decimal places
decimal separator = ','
thousands separator = '.'

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [v1.1]

Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};



Usage

(123456789.12345).formatMoney(2, '.', ',');

Comments on this post

dick posts on May 22, 2006 at 13:11
n = 1.9984 returns "1,00" instead of "2,00" when rounded to two decimals...
jonasraoni posts on Aug 10, 2006 at 16:48
I have no time to fix it haha, but it's easy =)
jonasraoni posts on Apr 11, 2008 at 22:46
Ahhhh I fixed it in my site but forgot to update here, I've just updated =)~

You need to create an account or log in to post comments to this site.


Click here to browse all 5201 code snippets

Related Posts