ruby-on-railsruby-on-rails-4ruby-on-rails-4.1

Currency to number conversion rails


Rails 4.1 Ruby 2.0 Windows 8.1

I found the number_to_currency helper, but no currency_to_number. I am trying to convert something like $8,000 into a decimal. Are there any Rails helpers for that? Any ideas?

Comment:

I have been using this:

number.to_s.gsub(/[^\d\.]/, '').to_f

Which eliminates everything with the exception of numerals and the decimal point and also handles the accidental integer. I was wondering if I'm missing some sort of currency_to_number helper. It looks like I am not. I will accept one of the answers.


Solution

  • Jorge's answer is good, but I think you'll need to know how the currency is entered. This will require whitelisting more than black listing.

    def currency_to_number currency
     currency.to_s.gsub(/[$,]/,'').to_f
    end