如何将美元兑换成美分换取金钱宝石

问题描述 投票:0回答:4

如何将美元兑换成美分换取金钱宝石

我的数据库中有很多货币类型。

假设我的数据库中有这 3 项

  • 金额:100,币种:新台币
  • 金额:100,币种:USD
  • 金额:100,币种:日元

然后

Money.new(100, :NTD)
,结果是1元新台币,但实际上应该是100元。

USD

但是,

Money.new(100, :JPY)
,日元的结果只是
100 dollars
,正如我所料。

就我而言,我该如何处理这种情况。不可能让我的用户用新台币1美元打100。

在金额字段中,我只想保存美元单位的数字。

然而,金钱宝石似乎只接受

cents
作为其输入。

有什么好的做法可以解决我的问题吗?

ruby-on-rails-4 money-rails
4个回答
0
投票

这是我当前的解决方案,但我认为它闻起来很糟糕

我希望有一些解决方案可以击败我当前的解决方法

CurrencyUtil.money_to_target_currency(价格,from_currency,to_currency)

lib/currency_util.rb

module CurrencyUtil

  def self.dollar_to_cents(amount, raw_currency)
    currency = raw_currency.upcase.to_sym
    if [:TWD, :USD].include? currency
      cents = amount*100
    elsif [:JPY]
      cents = amount
    end
    return cents
  end

  def self.money_to_target_currency(amount_in_dollar, from_currency, to_currency)
    cents = dollar_to_cents(amount_in_dollar, from_currency)
    Money.new(cents, from_currency).exchange_to(to_currency)
  end

end

0
投票

如果你看一下钱宝石,在/config/currency_iso.json

{
  "Jpy": {
    "priority": 6,
    "iso_code": "JPY",
    "name": "Japanese Yen",
    "symbol": "¥",
    "alternate_symbols": ["円", "圓"],
    "subunit": null,
    "subunit_to_unit": 1,
    "symbol_first": true,
    "html_entity": "¥",
    "decimal_mark": ".",
    "thousands_separator": ",",
    "iso_numeric": "392",
    "smallest_denomination": 1
  }
}

你会看到的

"subunit_to_unit": 1 

因此在这种情况下,您应该使用

覆盖日元和新台币货币
"subunit_to_unit": 100        

这是我在 /config/initializers/money.rb 下的示例代码

  Money::Currency.register({
    "priority": 6,
    "iso_code": "JPY",
    "name": "Japanese Yen",
    "symbol": "¥",
    "alternate_symbols": ["円", "圓"],
    "subunit": "Sen",
    "subunit_to_unit": 100,
    "symbol_first": true,
    "html_entity": "¥",
    "decimal_mark": ".",
    "thousands_separator": ",",
    "iso_numeric": "392",
    "smallest_denomination": 1
 })

您可以在这里添加更多货币。希望这对您有帮助。


0
投票

该死,这花了我很长时间才弄清楚。非常棒的宝石,但也有同样的问题。这是我的解决方案:

# multiply amount to convert by the subunit for currency
amount = amount * Money::Currency.new(from_symbol).subunit_to_unit
amount_exchanged = Money.new(amount, from_symbol).exchange_to(to_symbol)

0
投票

问。如何将美元兑换成美分换钱宝石

=> 使用

to_money
方法

例如:

usd
100usd
等于
10000cents

100.to_money(:usd)       #=> #<Money fractional:10000 currency:USD>

jpy
100jpy
等于
100jpy

100.to_money(:jpy)       #=> #<Money fractional:100 currency:JPY>
© www.soinside.com 2019 - 2024. All rights reserved.