8

通貨が異なる金額の文字列があります。たとえば、

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

パターンに一貫性がないため、文字列と通貨から浮動小数点数のみを抽出したいと思います。

Rubyでこれを実現するにはどうすればよいですか?

4

2 に答える 2

19

この正規表現を使用して、投稿した2つの形式の浮動小数点数を照合できます。-

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

Rubularのデモを見る

于 2012-12-04T15:53:11.123 に答える
8

あなたはこれを試すことができます:

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

CIBoxのデモ

于 2012-12-04T15:55:09.743 に答える