Ruby string with USD “money” converted to number

ぃ、小莉子 提交于 2019-12-03 09:47:46

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

You can do:

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

or to_i if they're only dollars

You could use the Money gem

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

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!