How to extract float numbers from a string in ruby? [closed]

时间秒杀一切 提交于 2020-12-30 06:36:15

问题


I have string with an amount different currencies in it, e.g,

"454,54$", "Rs566.33", "discount 88,0$" etc.

The pattern is not consistent and I want to extract only float numbers from the string and the currency.

How I can achieve this in Ruby ?


回答1:


You can use this regex to match floating point numbers in the two formats you posted: -

(\d+[,.]\d+)

See Demo on Rubular




回答2:


you can try this:

["454,54$", "Rs566.33", "discount 88,0$", "some string"].each do |str|
  # making sure the string actually contains some float
  next unless float_match = str.scan(/(\d+[.,]\d+)/).flatten.first
  # converting matched string to float
  float = float_match.tr(',', '.').to_f
  puts "#{str} => %.2f" % float
end

# => 454,54$ => 454.54
# => Rs566.33 => 566.33
# => discount 88,0$ => 88.00

Demo on CIBox



来源:https://stackoverflow.com/questions/13706706/how-to-extract-float-numbers-from-a-string-in-ruby

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