Ruby string with USD "money" converted to number

randombits picture randombits · Dec 10, 2013 · Viewed 14.1k times · Source

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.

Answer

naikipl picture naikipl · Dec 10, 2013

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