问题
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.
回答1:
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
回答2:
You can do:
"$100.00".scan(/[.0-9]/).join().to_f
or to_i if they're only dollars
回答3:
You could use the Money gem
Money.parse("$100") == Money.new(10000, "USD")
回答4:
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.)
回答5:
def dollar_to_number(dollarPrice)
if dollarPrice
dollarPrice[1, dollarPrice.length].to_i
end
end
回答6:
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
来源:https://stackoverflow.com/questions/20484084/ruby-string-with-usd-money-converted-to-number