Created
June 2, 2012 13:15
-
-
Save hmans/2858354 to your computer and use it in GitHub Desktop.
Format currency values.
This file contains hidden or 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
# So I wrote this cute little currency view formatting helper. Enjoy. | |
# | |
# (On a side note, shortly after writing this, I decided to use the awesome | |
# Money gem in my project, rendering most of this code obsolete.) | |
# | |
def currency(v, options = {}) | |
options = { | |
:symbol => "€", | |
:separator => ".", | |
:decimal_separator => ",", | |
:format_string => "%{symbol} %{dollars}%{decimal_separator}%{cents}" | |
}.merge(options) | |
# Prepare value by converting, rounding and pushing through sprintf | |
v = sprintf("%.2f", v.to_f.round(2)) | |
# Split dollars and cents | |
dollars, cents = v.split('.') | |
# Go wild with them dollars! | |
dollars = dollars.reverse.gsub(/(\d{1,3})/, "#{options[:separator]}\\1").reverse.chomp('.') | |
# That's it. Format value and return. Party is over. | |
options[:format_string] % { | |
:symbol => options[:symbol], | |
:dollars => dollars, | |
:decimal_separator => options[:decimal_separator], | |
:cents => cents | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment