【问题标题】:How to display currency with humanized_money_with_symbol method? Like USD$ 100如何使用humanized_money_with_symbol 方法显示货币?像 100 美元
【发布时间】:2017-07-12 09:40:07
【问题描述】:

我想humanized_money_with_symbol 方法返回类似USD$ 100 的东西,而不仅仅是$ 100。另外我只想在货币符号为$ 时这样做,我们想让用户知道$ 何时是美元,何时是澳元。

【问题讨论】:

    标签: ruby-on-rails money-rails


    【解决方案1】:

    从未使用过MoneyRails,但它looks like humanized_money_with_symbol 只是调用humanized_money 合并symbol: true 到您传递给它的参数。

    然后,该助手依次在传入的货币对象上调用format,并传入您指定的选项。在Money gem 中,你可以传入一个:symbol 来渲染货币,例如

    m = Money.new('123', :gbp) # => #<Money fractional:123 currency:GBP>
    m.format( symbol: m.currency.to_s + ' ') # => "GBP 1.23"
    

    所以,如果你打电话

    humanized_money(Money.new('123', :usd), symbol: 'USD $')
    # => "USD $1.23"
    

    然后您可以在您的应用程序中设置一个辅助方法,以避免总是必须传递该符号,例如:

    def render_custom_currency(value, options = {})
      value.currency.iso_code == "USD" ? humanized_money(value, options.merge(symbol: 'USD $')) : humanized_money(value, options.merge(symbol: true))
    end
    

    这应该会让你得到你想做的事情。

    【讨论】:

      【解决方案2】:

      您可以覆盖 initializers/money.rb 中的 USD 配置,以将“USD”显示为符号的一部分:

      MoneyRails.configure do |config|
        config.register_currency = {
          "priority": 2,
          "iso_code": "USD",
          "name": "United States Dollar",
          "symbol": "USD $",
          "subunit": "Cent",
          "subunit_to_unit": 100,
          "symbol_first": true,
          "decimal_mark": ".",
          "thousands_separator": ",",
        }
      end
      

      重新启动服务器,您应该会看到“USD $100”。我不使用多种货币,但这应该会让您的其他货币正常显示。

      【讨论】:

        【解决方案3】:

        最后我使用了 MoneyRails gem 中的内置选项disambiguate: true

        要使用它,您可以调用如下方法:

        humanized_money_with_symbol(value, disambiguate: true)
        

        它是如何工作的一些例子是here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-29
          • 2015-03-06
          • 1970-01-01
          相关资源
          最近更新 更多