A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » JavaScript » Format Currency Submit one!

Format Currency

This function will round numbers to two decimal places, and ensure that the returned value has two decimal places. For example 12.006 will return 12.01, .3 will return 0.30, and 5 will return 5.00

function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

Subscribe to The Thread

  1. Chase Moskal says:

    If you want a smaller function:

    
    function currency(N){N=parseFloat(N);if(!isNaN(N))N=N.toFixed(2);else N='0.00';return N;}
    
    // >> currency("-14"): "-14.00"
    

    If you want a smaller, more inline alternative, you can do this:

    
    // Right after you declare your number (N), the rest of the line does the formatting.
    var N=24.686; N=parseFloat(N);if(!isNaN(N))N=N.toFixed(2);else N='0.00';
    // >> N: "24.69"
    

    -Chase

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---