randombits
randombits

Reputation: 48490

Ruby string with USD "money" converted to number

Is there currently a gem that's capable of taking strings, all in USD for this purpose, and converting them to a number? Some examples would be:

I know on the "5500" example I can just do "5500".to_i, but the spreadsheets being imported aren't consistent and some include commas and dollar signs while others do not. There a decent way of handling this across the board in Ruby?

I've tried something like money_string.scan(/\d/).join which seems to be fine, just worried I'll run into edge cases I haven't found yet, such as decimal places.

Upvotes: 25

Views: 18443

Answers (7)

Arthur Neves
Arthur Neves

Reputation: 12138

If you are using money-rails gem, you can do the following

irb(main):004:0> "$7,600".to_money("USD")
=> #<Money fractional:760000 currency:USD>
irb(main):005:0> "5500".to_money("USD")
=> #<Money fractional:550000 currency:USD>

Upvotes: 1

NM Pennypacker
NM Pennypacker

Reputation: 6952

You can use the Monetize gem:

pry(main)> Monetize.parse("$7,600").to_i
=> 7600

https://github.com/RubyMoney/monetize

pry(main)> Monetize.parse("$7,600").class
=> Money

Upvotes: 1

Vibhuti
Vibhuti

Reputation: 1634

def dollar_to_number(dollarPrice)
  if dollarPrice
    dollarPrice[1, dollarPrice.length].to_i
  end
end

Upvotes: 0

JosephL
JosephL

Reputation: 5973

You could use the Money gem

Money.parse("$100") == Money.new(10000, "USD")

Upvotes: 8

naikipl
naikipl

Reputation: 481

Why not remove all non-digit characters before calling .to_i

Example:

"$7,600".gsub(/\D/,'').to_i

And for a floating point number:

"$7,600.90".gsub(/[^\d\.]/, '').to_f

Upvotes: 48

Lenny
Lenny

Reputation: 5937

You can do:

"$100.00".scan(/[.0-9]/).join().to_f

or to_i if they're only dollars

Upvotes: 10

DougM
DougM

Reputation: 2888

You should be able to trim any non-numeric characters with a Ruby RegEx object. Sanitize your inputs to remove anything but numbers to the left of a decimal point, and then parse the numbers-only string as a number.

(And note that, if you're getting actual spreadsheets instead of CSV bunk, there's likely a value property you can read that ignores the text displayed on screen.)

Upvotes: 0

Related Questions