A Ruby Library for dealing with money and currency conversion.
A Ruby Library for dealing with money and currency conversion.
⚠️ Please read the upgrade guides before upgrading to a new major version.
If you miss String parsing, check out the new monetize gem.
See the Contribution Guidelines
A Ruby Library for dealing with money and currency conversion.
Money class which encapsulates all information about a certain
amount of money, such as its value and its currency.Money::Currency class which encapsulates all information about
a monetary unit.Money::Currency instances providing a high level of
flexibility.Install stable releases with the following command:
gem install money
The development version (hosted on Github) can be installed with:
git clone git://github.com/RubyMoney/money.git
cd money
bin/rake install
…
Currencies are consistently represented as instances of Money::Currency.
The most part of Money APIs allows you to supply either a String or a
Money::Currency.
Money.from_cents(1000, "USD") == Money.from_cents(1000, Money::Currency.new("USD"))
Money.from_cents(1000, "EUR").currency == Money::Currency.new("EUR")
A Money::Currency instance holds all the information about the currency,
including the currency symbol, name and much more.
currency = Money.from_cents(1000, "USD").currency
currency.iso_code #=> "USD"
currency.name #=> "United States Dollar"
currency.cents_based? #=> true
To define a new Money::Currency use Money::Currency.register as shown
below.
curr = {
priority: 1,
iso_code: "USD",
iso_numeric: "840",
name: "United States Dollar",
symbol: "$",
subunit: "Cent",
subunit_to_unit: 100,
decimal_mark: ".",
thousands_separator: ","
}
Money::Currency.register(curr)
The pre-defined set of attributes includes:
:priority a numerical value you can use to sort/group the currency list:iso_code the international 3-letter code as defined by the ISO 4217 standard:iso_numeric the international 3-digit code as defined by the ISO 4217 standard:name the currency name:symbol the currency symbol (UTF-8 encoded):subunit the name of the fractional monetary unit:subunit_to_unit the proportion between the unit and the subunit:decimal_mark character between the whole and fraction amounts:thousands_separator character between each thousands placeAll attributes except :iso_code are optional. Some attributes, such as
:symbol, are used by the Money class to print out a representation of the
object. Other attributes, such as :name or :priority, exist to provide a
basic API you can take advantage of to build your application.
The priority attribute is an arbitrary numerical value you can assign to the
Money::Currency and use in sorting/grouping operation.
For instance, let's assume your Rails application needs to render a currency selector like the one available here. You can create a couple of custom methods to return the list of major currencies and all currencies as follows:
# Returns an array of currency id where
# priority < 10
def major_currencies(hash)
hash.inject([]) do |array, (id, attributes)|
priority = attributes[:priority]
if priority && priority < 10
array[priority] ||= []
array[priority] << id
end
array
end.compact.flatten
end
# Returns an array of all currency id
def all_currencies(hash)
hash.keys
end
major_currencies(Money::Currency.table)
# => [:usd, :eur, :gbp, :aud, :cad, :jpy]
all_currencies(Money::Currency.table)
# => [:aed, :afn, :all, ...]
A default currency is not set by default. If a default currency is not set, it will raise an error when you try to initialize a Money object without explicitly passing a currency or parse a string that does not contain a currency. You can set a default currency for your application by using:
Money.default_currency = Money::Currency.new("CAD")
If you use Rails, then config/initializers/money.rb is a very good place to put this.
The exponent of a money value is the number of digits after the decimal
separator (which separates the major unit from the minor unit). See e.g.
ISO 4217 for more
information. You can find the exponent (as an Integer) by
Money::Currency.new("USD").exponent # => 2
Money::Currency.new("JPY").exponent # => 0
Money::Currency.new("MGA").exponent # => 1
To find a given currency by ISO 4217 numeric code (three digits) you can do
Money::Currency.find_by_iso_numeric(978) #=> Money::Currency.new(:eur)
Exchanging money is performed through an exchange bank object. The default exchange bank object requires one to manually specify the exchange rate. Here's an example of how it works:
Money.add_rate("USD", "CAD", 1.24515)
Money.add_rate("CAD", "USD", 0.803115)
Money.us_dollar(100).exchange_to("CAD") # => Money.from_cents(124, "CAD")
Money.ca_dollar(100).exchange_to("USD") # => Money.from_cents(80, "USD")
Comparison and arithmetic operations work as expected:
Money.from_cents(1000, "USD") <=> Money.from_cents(900, "USD") # => 1; 9.00 USD is smaller
Money.from_cents(1000, "EUR") + Money.from_cents(10, "EUR") == Money.from_cents(1010, "EUR")
Money.add_rate("USD", "EUR", 0.5)
Money.from_cents(1000, "EUR") + Money.from_cents(1000, "USD") == Money.from_cents(1500, "EUR")
The default bank is initialized with an in-memory store for exchange rates.
Money.default_bank = Money::Bank::VariableExchange.new(Money::RatesStore::Memory.new)
You can pass your own store implementation, i.e. for storing and retrieving rates off a database, file, cache, etc.
Money.default_bank = Money::Bank::VariableExchange.new(MyCustomStore.new)
Stores must implement the following interface:
…
The following example implements an ActiveRecord store to save exchange rates to a database.
…
The following example implements a Redis store to save exchange rates to a redis database.
…
Now you can use it with the default bank.
# For Rails 6 pass model name as a string to make it compatible with zeitwerk
# Money.default_bank = Money::Bank::VariableExchange.new("ExchangeRate")
Money.default_bank = Money::Bank::VariableExchange.new(ExchangeRate)
# Add to the underlying store
Money.default_bank.add_rate('USD', 'CAD', 0.9)
# Retrieve from the underlying store
Money.default_bank.get_rate('USD', 'CAD') # => 0.9
# Exchanging amounts just works.
Money.from_cents(1000, 'USD').exchange_to('CAD') #=> #<Money fractional:900 currency:CAD>
There is nothing stopping you from creating store objects which scrapes
XE for the current rates or just returns rand(2):
Money.default_bank = Money::Bank::VariableExchange.new(StoreWhichScrapesXeDotCom.new)
You can also implement your own Bank to calculate exchanges differently. Different banks can share Stores.
Money.default_bank = MyCustomBank.new(Money::RatesStore::Memory.new)
If you wish to disable automatic currency conversion to prevent arithmetic when currencies don't match:
Money.disallow_currency_conversion!
The following is a list of Money.gem compatible currency exchange rate implementations.
There are several formatting rules for when Money#format is called. For more information, check out the formatting module source, or read the latest release's rdoc version.
If you wish to format money according to the EU's Rules for expressing monetary units in either English, Irish, Latvian or Maltese:
m = Money.from_cents('123', :gbp) # => #<Money fractional:123 currency:GBP>
m.format(symbol: m.currency.to_s + ' ') # => "GBP 1.23"
If you would like to customize currency symbols to avoid ambiguity between currencies, you can:
Money::Currency.table[:hkd][:symbol] = 'HK$'
By default, Money objects are rounded to the nearest cent and the additional precision is not preserved:
Money.from_amount(2.34567).format #=> "$2.35"
To retain the additional precision, you will also need to set infinite_precision to true.
Money.default_infinite_precision = true
Money.from_amount(2.34567).format #=> "$2.34567"
To round to the nearest cent (or anything more precise), you can use the round method. However, note that the round method on a Money object does not work the same way as a normal Ruby Float object. Money's round method accepts different arguments. The first argument to the round method is the rounding mode, while the second argument is the level of precision relative to the cent.
# Float
2.34567.round #=> 2
2.34567.round(2) #=> 2.35
# Money
Money.default_infinite_precision = true
Money.from_cents(2.34567).format #=> "$0.0234567"
Money.from_cents(2.34567).round.format #=> "$0.02"
Money.from_cents(2.34567).round(BigDecimal::ROUND_DOWN, 2).format #=> "$0.0234"
You can set the default rounding mode by passing one of the BigDecimal mode enumerables like so:
Money.rounding_mode = BigDecimal::ROUND_HALF_EVEN
See BigDecimal::ROUND_MODE for more information.
To round to the nearest cash value in currencies without small denominations:
Money.from_cents(11_11, "CHF").to_nearest_cash_value.format # => "CHF 11.10"
To integrate money in a Rails application use money-rails.
For deprecated methods of integrating with Rails, check the wiki.
In order to localize formatting you can use I18n gem:
Money.locale_backend = :i18n
With this enabled a thousands separator and a decimal mark will get looked up in your I18n trans
No open issues yet, or sync has not completed.