Created
June 29, 2011 04:42
-
-
Save trivektor/1053168 to your computer and use it in GitHub Desktop.
Convert number to currency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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