Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 700
EastsideDev Avatar asked Jun 11 '14 21:06

EastsideDev


3 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
like image 156
chris raethke Avatar answered Nov 01 '22 06:11

chris raethke


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.

like image 21
Jorge de los Santos Avatar answered Nov 01 '22 06:11

Jorge de los Santos


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
like image 22
Snarf Avatar answered Nov 01 '22 06:11

Snarf