我有一些不同货币的字符串,例如
"454,54$", "Rs566.33", "discount 88,0$" etc.
模式不一致,我想从字符串和货币中仅提取浮点数。
我如何在Ruby中实现这一目标?
答案 0 :(得分:17)
答案 1 :(得分:6)
你可以试试这个:
["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