加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 处理Ruby on Rails中的国际货币输入

发布时间:2020-12-16 22:37:58 所属栏目:百科 来源:网络整理
导读:我有 an application处理货币输入.但是,如果你在美国,你可以输入一个号码为12,345.67;在法国,可能是12.345,67. 在Rails中有一个简单的方法来适应货币进入一个地区吗? 请注意,我不是要显示货币(ala number_to_currency),我正在寻找一个用货币字符串输入的人,
我有 an application处理货币输入.但是,如果你在美国,你可以输入一个号码为12,345.67;在法国,可能是12.345,67.

在Rails中有一个简单的方法来适应货币进入一个地区吗?

请注意,我不是要显示货币(ala number_to_currency),我正在寻找一个用货币字符串输入的人,并将其转换成十进制.

解决方法

你可以给一个镜头:
def string_to_float(string)

      string.gsub!(/[^d.,]/,'')          # Replace all Currency Symbols,Letters and -- from the string

      if string =~ /^.*[.,]d{1}$/       # If string ends in a single digit (e.g.,2)
        string = string + "0"             # make it,20 in order for the result to be in "cents"
      end

      unless string =~ /^.*[.,]d{2}$/   # If does not end in,00 / .00 then
        string = string + "00"            # add trailing 00 to turn it into cents
      end

      string.gsub!(/[.,'')            # Replace all (.) and (,) so the string result becomes in "cents"  
      string.to_f / 100                   # Let to_float do the rest
   end

和测试案例:

describe Currency do
  it "should mix and match" do
    Currency.string_to_float("$1,000.50").should eql(1000.50)
    Currency.string_to_float("                        

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读