问题
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