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?
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.
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
The number_to_currency formats a number. If you are trying to convert something like $8.000 into a number you might want to create a new method to parse the string into a number. something like:
result = "$8.000".gsub(/[^\d]/, '').to_f
For an improved conversion of something like:
"$8.000,00"
You are going to need a better regexp.
I just tested this in IRB you will want to put this in some sort of method for use with Rails though.
price = "$8,000.90"
price.match(/(\d.+)/)[1].gsub(',','').to_f
#=> 8000.9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With