DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Format Currency //Javascript Function

07.01.2005
| 33970 views |
  • submit to reddit
        <a href="http://www.jsfromhell.com/number/fmt-money">
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]
</a>


//+ 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

Snippets Manager replied on Mon, 2012/05/07 - 1:12pm

Ahhhh I fixed it in my site but forgot to update here, I've just updated =)~

Snippets Manager replied on Mon, 2012/05/07 - 1:12pm

I have no time to fix it haha, but it's easy =)

d m replied on Mon, 2006/05/22 - 12:10pm

n = 1.9984 returns "1,00" instead of "2,00" when rounded to two decimals...