SkillAgentSearch skills...

Money

A Ruby Library for dealing with money and currency conversion.

Install / Use

/learn @RubyMoney/Money
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

RubyMoney - Money

Gem Version Ruby Inline docs License

⚠️ Please read the upgrade guides before upgrading to a new major version.

If you miss String parsing, check out the new monetize gem.

Contributing

See the Contribution Guidelines

Introduction

A Ruby Library for dealing with money and currency conversion.

Features

  • Provides a Money class which encapsulates all information about a certain amount of money, such as its value and its currency.
  • Provides a Money::Currency class which encapsulates all information about a monetary unit.
  • Represents monetary values as integers, in cents. This avoids floating point rounding errors.
  • Represents currency as Money::Currency instances providing a high level of flexibility.
  • Provides APIs for exchanging money from one currency to another.

Resources

Notes

  • Your app must use UTF-8 to function with this library. There are a number of non-ASCII currency attributes.

Downloading

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
rake install

Usage

require 'money'

# explicitly define locales
I18n.config.available_locales = :en
Money.locale_backend = :i18n

# 10.00 USD
money = Money.from_cents(1000, "USD")
money.cents     #=> 1000
money.currency  #=> Currency.new("USD")

# Comparisons
Money.from_cents(1000, "USD") == Money.from_cents(1000, "USD")   #=> true
Money.from_cents(1000, "USD") == Money.from_cents(100, "USD")    #=> false
Money.from_cents(1000, "USD") == Money.from_cents(1000, "EUR")   #=> false
Money.from_cents(1000, "USD") != Money.from_cents(1000, "EUR")   #=> true

# Arithmetic
Money.from_cents(1000, "USD") + Money.from_cents(500, "USD") == Money.from_cents(1500, "USD")
Money.from_cents(1000, "USD") - Money.from_cents(200, "USD") == Money.from_cents(800, "USD")
Money.from_cents(1000, "USD") / 5                            == Money.from_cents(200, "USD")
Money.from_cents(1000, "USD") * 5                            == Money.from_cents(5000, "USD")

# Unit to subunit conversions
Money.from_amount(5, "USD") == Money.from_cents(500, "USD")  # 5 USD
Money.from_amount(5, "JPY") == Money.from_cents(5, "JPY")    # 5 JPY
Money.from_amount(5, "TND") == Money.from_cents(5000, "TND") # 5 TND

# Currency conversions
some_code_to_setup_exchange_rates
Money.from_cents(1000, "USD").exchange_to("EUR") == Money.from_cents(some_value, "EUR")

# Swap currency
Money.from_cents(1000, "USD").with_currency("EUR") == Money.from_cents(1000, "EUR")

# Formatting (see Formatting section for more options)
Money.from_cents(100, "USD").format #=> "$1.00"
Money.from_cents(100, "GBP").format #=> "£1.00"
Money.from_cents(100, "EUR").format #=> "€1.00"

Currency

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 place

All 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.

:priority

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, ...]

Default Currency

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.

Currency Exponent

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

Currency Lookup

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)

Currency Exchange

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")

Exchange rate stores

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:

# Add new exchange rate.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
# @param [Numeric] rate Exchange rate. ex. 0.0016
#
# @return [Numeric] rate.
def add_rate(iso_from, iso_to, rate); end

# Get rate. Must be idempotent. i.e. adding the same rate must not produce duplicates.
# @param [String] iso_from Currency ISO code. ex. 'USD'
# @param [String] iso_to Currency ISO code. ex. 'CAD'
#
# @return [Numeric] rate.
def get_rate(iso_from, iso_to); end

# Iterate over rate tuples (iso_from, iso_to, rate)
#
# @yieldparam iso_from [String] Currency ISO string.
# @yieldparam iso_to [String] Currency ISO string.
# @yieldparam rate [Numeric] Exchange rate.
#
# @return [Enumerator]
#
# @example
#   store.each_rate do |iso_from, iso_to, rate|
#     puts [iso_from, iso_to, rate].join
#   end
def each_rate(&block); end

# Wrap store operations in a thread-safe transaction
# (or IO or Database transaction, depending on your implementation)
#
# @yield [n] Block that will be wrapped in tran

Related Skills

View on GitHub
GitHub Stars2.8k
CategoryDevelopment
Updated12m ago
Forks639

Languages

Ruby

Security Score

100/100

Audited on Mar 25, 2026

No findings