Ruby string with USD "money" converted to number
Asked Answered
T

7

25

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.

Toulouselautrec answered 10/12, 2013 at 1:4 Comment(0)
A
47

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
Anticlinal answered 10/12, 2013 at 1:21 Comment(2)
removes '-' if the amount is negative.Enugu
If you need to account for negatives, then just add '-' to the regular expression in the floating point example above. "-$7,600.90".gsub(/[^\d\.-]/,'').to_f or "-$7,600.90".gsub(/[^\d\.-]/,'').to_iAnticlinal
P
11

You can do:

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

or to_i if they're only dollars

Pearson answered 10/12, 2013 at 1:10 Comment(1)
Didn't read the last part of your question. I think this is probably the best choice and it should always work. Using \d is fine too obviously.Pearson
S
8

You could use the Money gem

Money.parse("$100") == Money.new(10000, "USD")
Sale answered 10/12, 2013 at 1:51 Comment(1)
Since version 6.0.0, parse was deprecated from Money and is now part of Monetize github.com/RubyMoney/monetizeFranklyn
A
1

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
Alienage answered 23/7, 2019 at 11:39 Comment(0)
V
1

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>
Vibration answered 18/2, 2022 at 19:55 Comment(0)
P
0

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.)

Priapus answered 10/12, 2013 at 1:10 Comment(0)
S
0
def dollar_to_number(dollarPrice)
  if dollarPrice
    dollarPrice[1, dollarPrice.length].to_i
  end
end
Solo answered 11/1, 2015 at 15:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.