Skip to content

Instantly share code, notes, and snippets.

@trivektor
Created June 29, 2011 04:42
Show Gist options
  • Save trivektor/1053168 to your computer and use it in GitHub Desktop.
Save trivektor/1053168 to your computer and use it in GitHub Desktop.
Convert number to currency
# Taken from http://codesnippets.joyent.com/posts/show/1812
# takes a number and options hash and outputs a string in any currency format
def currencify(number, options={})
# :currency_before => false puts the currency symbol after the number
# default format: $12,345,678.90
options = {:currency_symbol => "$", :delimiter => ",", :decimal_symbol => ".", :currency_before => true}.merge(options)
# split integer and fractional parts
int, frac = ("%.2f" % number).split('.')
# insert the delimiters
int.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
if options[:currency_before]
options[:currency_symbol] + int + options[:decimal_symbol] + frac
else
int + options[:decimal_symbol] + frac + options[:currency_symbol]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment