Skip to content

Instantly share code, notes, and snippets.

@rpheath
Created January 28, 2009 15:37
Show Gist options
  • Select an option

  • Save rpheath/54011 to your computer and use it in GitHub Desktop.

Select an option

Save rpheath/54011 to your computer and use it in GitHub Desktop.
// jQuery plugin:
// converts a float number as text in some element
// into US currency
//
// Ex:
// <span id="price">1234988.3400</span>
//
// $('span#price').toCurrency()
// => <span id="price">$1,234,988.34</span>
(function($) {
$.fn.toCurrency = function() {
return this.each(function() {
var currency = Math.abs($(this).text()).toFixed(2),
dollars = currency.split('.')[0],
cents = currency.split('.')[1]
for (var i = 0; i < Math.floor((dollars.length - (1 + i)) / 3); i++)
dollars = dollars.substring(0, dollars.length - (4 * i + 3)) + ',' +
dollars.substring(dollars.length - (4 * i + 3))
$(this).text('$' + dollars + '.' + cents)
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment