如何解析字符串Ruby中的复杂货币值 [英] How to parse through complex currency value from a string Ruby

查看:86
本文介绍了如何解析字符串Ruby中的复杂货币值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须解析一组复杂的货币值字符串.某些特殊情况也需要考虑.

I have to parse through a collection of complex currency value strings.There are certain unique cases that also need to be taken into consideration.

其中有一些(左:要解析的字符串,右:所需的返回值):

Here are some of them (left: string to parse, right: desired return value):

"$1,950,000"          #=> "1950000
"$750,000"            #=> "750000"
"$1,433,000[2]"       #=> "1433000"
"$1.3 million"        #=> "1300000"
"$2.183 million[4]"   #=> "2183000"
"US$1,644,736 (est.)" #=> "1644736"

我可以拆分字符串,然后对每种特殊情况使用条件语句逻辑,但是我想知道是否存在一种更抽象"的方式来解析这些字符串.

I could split the string and then use conditional statement logic for every special case but I am wondering if there is a more "abstract" way to parse through these strings.

更新

我签出了这个问题,它有一些好处但是,百万"部分未得到解释.看,如果字符串是"120万美元",我知道在之后".我总共需要6个数字(在这种情况下为字符串数字),因此将添加4个零.如果我有"218.3万美元",我知道我需要添加3个零,以便在."之后总共有6位数字.

I checked out this question which has some good explanation however the "million" part misses. See, if the string is "$1.2 million" I know that after the "." I need a total of 6 digits (or string digits in this case) therefore 4 zero will be added. If I have "$2.183 million" I know that i'll need to add 3 zeros so that there is a total of 6 digits after the "."

推荐答案

只需提取单元,如million:

s = '"$1,950,000"          #=> "1950000
"$750,000"            #=> "750000"
"$1,433,000[2]"       #=> "1433000"
"$1.3 million"        #=> "1300000"
"$2.183 million[4]"   #=> "2183000"
"US$1,644,736 (est.)" #=> "1644736"'

s.scan(/[\$£](\d{1,3}(,\d{3})*(\.\d*)?)( hundred| thousand| million| billion)?/).each do |m|
  number = m[0].gsub(',', '').to_f
  unit = m[3]
  multiplier = 1

  if unit == ' hundred' then
    multiplier = 1e2
  elsif unit == ' thousand' then
    multiplier = 1e3
  elsif unit == ' million' then
    multiplier = 1e6
  elsif unit == ' billion' then
    multiplier = 1e9
  end

  puts number * multiplier
end

打印

1950000.0
750000.0
1433000.0
1300000.0
2183000.0
1644736.0

这篇关于如何解析字符串Ruby中的复杂货币值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆