Monitary precision of a Ruby float
I looked around and couldn’t seem to find a way to easily change the precision of a Ruby Float object to 2 decimals so I can use it as a dollar amount. I feel bad about posting this because I borrowed some of the code from another site but lost the link to it. Instead of extending the Float class I just wrote a function to do it for me. It takes a Float object and returns string. I returned a string instead of a Float because I’m using it in the view and outputting the result anyway. Anyway, here’s the helper function.
def monetize(number)
splitnum = number.to_s.split(".")[0]
scale = number.to_s.split(".")[1][0..1]
while scale.length < 2
scale = scale + '0'
end
"#{splitnum}.#{scale}"
end

June 18th, 2007 at 7:26 pm
I just found:
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M000520
number_to_currency
Which does exactly what i want it to so I’m scrapping my proprietary monetize function.