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

One Response to “Monitary precision of a Ruby float”

  1. admin Says:

    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.

Leave a Reply