EastsideDev
EastsideDev

Reputation: 6659

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.

Upvotes: 7

Views: 9009

Answers (4)

chris raethke
chris raethke

Reputation: 435

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

Upvotes: 15

aruanoc
aruanoc

Reputation: 867

There is no built in method, but a method like this would do the trick

def currency_to_number(currency_value)
  (currency_value.is_a? String) ? currency_value.scan(/[.0-9]/).join.to_d : currency_value
end

This method returns a Decimal if a String is passed, if you want a float, use ".to_f" instead.

Upvotes: 1

Snarf
Snarf

Reputation: 2361

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

Upvotes: 1

Jorge de los Santos
Jorge de los Santos

Reputation: 4643

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.

Upvotes: 1

Related Questions