Ruby string with USD "money" converted to number

Viewed 16432

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:

  • "$7,600" would turn into 7600
  • "5500" would turn into 5500

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.

7 Answers

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>
Related