如何正确使用货币兑换 gem

How to exchange correctly using the Money gem

我使用 Money gem 来处理不同的货币。我发现 "JPY" 货币有一个奇怪的行为。

我有以下费率:

config.add_rate('USD', 'EUR', 0.92)
config.add_rate('USD', 'JPY', 123.0)

尝试兑换货币时,我得到了奇怪的结果:

10.to_money.exchange_to('EUR')
=> #<Money fractional:920 currency:EUR>

10.to_money.exchange_to('JPY')
=> #<Money fractional:1230 currency:JPY>

"JPY" 转换应该是 #<Money fractional:123000 currency:JPY>。对正在发生的事情有什么想法吗?

这实际上取决于 Currency 的定义。下面的代码显示 10 美元确实等于 1230 日元。

require "rails"
require "money-rails"

Money.add_rate('USD', 'EUR', 0.92)
Money.add_rate('USD', 'JPY', 123.0)

p 10.to_money.exchange_to('JPY') == Money.new(1230,"JPY")
#=> true

如果您检查 JPY 货币

,您认为应该看到 123000 的期望可能不正确
p Money.new(1230,"JPY").currency

#<Money::Currency id: jpy, priority: 6, symbol_first: true, thousands_separator: ,, html_entity: &#x00A5;, decimal_mark: ., name: Japanese Yen, symbol: ¥, subunit_to_unit: 1, exponent: 0.0, iso_code: JPY, iso_numeric: 392, subunit: , smallest_denomination: 1>

Currency 定义中要注意的重要字段是 subunit_to_unit: 1 的值。根据文档:

:subunit_to_unit the proportion between the unit and the subunit

这意味着如果是日元,显示的值是日元,不需要像美元或欧元那样乘以 100。

p 10.to_money.exchange_to('EUR')
#=> #<Money fractional:920 currency:EUR>
p 10.to_money.exchange_to('JPY')
#=> #<Money fractional:1230 currency:JPY>

以下是欧元的货币定义

#<Money::Currency id: eur, priority: 2, symbol_first: true, thousands_separator: ., html_entity: &#x20AC;, decimal_mark: ,, name: Euro, symbol: €, subunit_to_unit: 100, exponent: 2.0, iso_code: EUR, iso_numeric: 978, subunit: Cent, smallest_denomination: 1>

如果是欧元,subunit_to_unit: 100 表示该值以美分(或等值)为单位