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

标签 ruby-on-rails internationalization 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("€ 1.000,50").should eql(1000.50)
    Currency.string_to_float("€ 1.000,--").should eql(1000.to_f)
    Currency.string_to_float("$ 1,000.--").should eql(1000.to_f)    
  end     

  it "should strip the € sign" do
    Currency.string_to_float("€1").should eql(1.to_f)
  end

  it "should strip the $ sign" do
    Currency.string_to_float("$1").should eql(1.to_f)
  end

  it "should strip letter characters" do
    Currency.string_to_float("a123bc2").should eql(1232.to_f)
  end

  it "should strip - and --" do
    Currency.string_to_float("100,-").should eql(100.to_f)
    Currency.string_to_float("100,--").should eql(100.to_f)
  end

  it "should convert the , as delimitor to a ." do
    Currency.string_to_float("100,10").should eql(100.10)
  end

  it "should convert ignore , and . as separators" do
    Currency.string_to_float("1.000,10").should eql(1000.10)
    Currency.string_to_float("1,000.10").should eql(1000.10)
  end

  it "should be generous if you make a type in the last '0' digit" do
    Currency.string_to_float("123,2").should eql(123.2)
  end

关于ruby-on-rails - 在 Ruby on Rails 中处理国际货币输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1669214/

相关文章:

ruby-on-rails - 将group_by与fields_for和accepts_nested_attributes_for一起使用

ruby-on-rails - 带有空路径和助手的路由

.net - 有关重构现有 .net 应用程序以支持本地化的技巧?

internationalization - Polymer.dart 中国际化字符串中的 HTML 标签

currency - 货币符号有iso标准吗?

c# - .net 中各种语言的货币符号

ruby-on-rails - Rails 使用参数测试 Controller 私有(private)方法

ruby-on-rails - Ruby 将字符串和整数放在同一行

windows - 如何在 Windows 中使用 enable pseudo-locale 进行测试?

读取R中的csv文件,货币列为数字