如何从ruby中的字符串中提取浮点数?

时间:2022-04-27 19:32:00

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 ?

我如何在Ruby中实现这一目标?

2 个解决方案

#1


17  

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

您可以使用此正则表达式匹配您发布的两种格式的浮点数: -

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

See Demo on Rubular

请参阅Rubular演示

#2


6  

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

#1


17  

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

您可以使用此正则表达式匹配您发布的两种格式的浮点数: -

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

See Demo on Rubular

请参阅Rubular演示

#2


6  

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