How to extract floating point numbers from a string in ruby?

I have a line with the number of different currencies, for example

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

The pattern is not consistent, and I want to extract only floating point numbers from string and currency.

How can I achieve this in Ruby?

+6
source share
2 answers

You can use this regular expression to match floating point numbers in two published formats: -

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

See the demo on Rubular

+17
source

you can try the following:

 ["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

+6
source

All Articles