Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Created October 16, 2008 01:27
Show Gist options
  • Select an option

  • Save subtleGradient/17045 to your computer and use it in GitHub Desktop.

Select an option

Save subtleGradient/17045 to your computer and use it in GitHub Desktop.
formatCurrency( 123 | 123.321 ) -> ( "$0" | "<b class="neg">-$123<i class="cents c123">.123</i></b>" )
function formatCurrency(num){
num = (num||'0').toString().replace(/\$|\,/g,'');
if(isNaN(num)) num = "0";
if(num+0 == 0) return '$0';
var sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
var cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10) cents = "0" + cents;
numlength = num.length;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return [
'<span class="',
sign?' pos':' neg',
' l', numlength,
'">',
sign ? '' : '-',
'$',
num,
'<i class="cents c'+cents+'">.', cents, '</i>',
'</span>'
].join('');
}
document.write(formatCurrency(0) +'\n')
document.write(formatCurrency(1) +'\n')
document.write(formatCurrency(-1) +'\n')
document.write(formatCurrency(0.5) +'\n')
document.write(formatCurrency(1.5) +'\n')
document.write(formatCurrency(-1.5) +'\n')
document.write(formatCurrency(999999999999) +'\n')
document.write(formatCurrency(5555.5555) +'\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment