1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
|
# RubyMoney - Money
[](https://rubygems.org/gems/money)
[](https://github.com/RubyMoney/money/actions/workflows/ruby.yml)
[](https://rubymoney.github.io/money/)
[](https://opensource.org/license/MIT)
⚠️ Please read the [upgrade guides](#upgrade-guides) before upgrading to a new major version.
If you miss String parsing, check out the new [monetize gem](https://github.com/RubyMoney/monetize).
## Contributing
See the [Contribution Guidelines](https://github.com/RubyMoney/money/blob/main/CONTRIBUTING.md)
## 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
- [Website](https://rubymoney.github.io/money/)
- [API Documentation](https://www.rubydoc.info/gems/money/frames)
- [Git Repository](https://github.com/RubyMoney/money)
### 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
```ruby
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`.
```ruby
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.
```ruby
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.
```ruby
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](https://finance.yahoo.com/currency-converter/). You can create a couple of
custom methods to return the list of major currencies and all currencies as
follows:
```ruby
# 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:
```ruby
Money.default_currency = Money::Currency.new("CAD")
```
If you use [Rails](https://github.com/RubyMoney/money/tree/main#ruby-on-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](https://www.iso.org/iso-4217-currency-codes.html) for more
information. You can find the exponent (as an `Integer`) by
```ruby
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
```ruby
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:
```ruby
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:
```ruby
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.
```ruby
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.
```ruby
Money.default_bank = Money::Bank::VariableExchange.new(MyCustomStore.new)
```
Stores must implement the following interface:
```ruby
# 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 transaction.
#
# @example
# store.transaction do
# store.add_rate('USD', 'CAD', 0.9)
# store.add_rate('USD', 'CLP', 0.0016)
# end
def transaction(&block); end
# Serialize store and its content to make Marshal.dump work.
#
# Returns an array with store class and any arguments needed to initialize the store in the current state.
# @return [Array] [class, arg1, arg2]
def marshal_dump; end
```
The following example implements an `ActiveRecord` store to save exchange rates to a database.
```ruby
# rails g model exchange_rate from:string to:string rate:float
class ExchangeRate < ApplicationRecord
def self.get_rate(from_iso_code, to_iso_code)
rate = find_by(from: from_iso_code, to: to_iso_code)
rate&.rate
end
def self.add_rate(from_iso_code, to_iso_code, rate)
exrate = find_or_initialize_by(from: from_iso_code, to: to_iso_code)
exrate.rate = rate
exrate.save!
end
def self.each_rate
return find_each unless block_given?
find_each do |rate|
yield rate.from, rate.to, rate.rate
end
end
def self.marshal_dump
[self]
end
end
```
The following example implements a `Redis` store to save exchange rates to a redis database.
```ruby
class RedisRateStore
INDEX_KEY_SEPARATOR = '_TO_'.freeze
# Using second db of the redis instance
# because sidekiq uses the first db
REDIS_DATABASE = 1
# Using Hash to store rates data
REDIS_STORE_KEY = 'rates'
def initialize
conn_url = "#{Rails.application.credentials.redis_server}/#{REDIS_DATABASE}"
@connection = Redis.new(url: conn_url)
end
def add_rate(iso_from, iso_to, rate)
@connection.hset(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to), rate)
end
def get_rate(iso_from, iso_to)
@connection.hget(REDIS_STORE_KEY, rate_key_for(iso_from, iso_to))
end
def each_rate
rates = @connection.hgetall(REDIS_STORE_KEY)
return to_enum(:each_rate) unless block_given?
rates.each do |key, rate|
iso_from, iso_to = key.split(INDEX_KEY_SEPARATOR)
yield iso_from, iso_to, rate
end
end
def transaction
yield
end
private
def rate_key_for(iso_from, iso_to)
[iso_from, iso_to].join(INDEX_KEY_SEPARATOR).upcase
end
end
```
Now you can use it with the default bank.
```ruby
# 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](https://www.xe.com) for the current rates or just returns `rand(2)`:
```ruby
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.
```ruby
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:
```ruby
Money.disallow_currency_conversion!
```
### Implementations
The following is a list of Money.gem compatible currency exchange rate
implementations.
- [eu_central_bank](https://github.com/RubyMoney/eu_central_bank)
- [google_currency](https://github.com/RubyMoney/google_currency)
- [currencylayer](https://github.com/askuratovsky/currencylayer)
- [nordea](https://github.com/matiaskorhonen/nordea)
- [nbrb_currency](https://github.com/slbug/nbrb_currency)
- [money-currencylayer-bank](https://github.com/phlegx/money-currencylayer-bank)
- [money-open-exchange-rates](https://github.com/spk/money-open-exchange-rates)
- [money-historical-bank](https://github.com/atwam/money-historical-bank)
- [russian_central_bank](https://github.com/rmustafin/russian_central_bank)
- [money-uphold-bank](https://github.com/subvisual/money-uphold-bank)
## Formatting
There are several formatting rules for when `Money#format` is called. For more information, check out the [formatting module source](https://github.com/RubyMoney/money/blob/main/lib/money/money/formatter.rb), or read the latest release's [rdoc version](https://www.rubydoc.info/gems/money/Money/Formatter).
If you wish to format money according to the EU's [Rules for expressing monetary units](https://style-guide.europa.eu/en/content/-/isg/topic?identifier=7.3.3-rules-for-expressing-monetary-units#id370303__id370303_PositionISO) in either English, Irish, Latvian or Maltese:
```ruby
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:
```ruby
Money::Currency.table[:hkd][:symbol] = 'HK$'
```
## Rounding
By default, `Money` objects are rounded to the nearest cent and the additional precision is not preserved:
```ruby
Money.from_amount(2.34567).format #=> "$2.35"
```
To retain the additional precision, you will also need to set `infinite_precision` to `true`.
```ruby
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.
```ruby
# 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:
```ruby
Money.rounding_mode = BigDecimal::ROUND_HALF_EVEN
```
See [BigDecimal::ROUND_MODE](https://ruby-doc.org/3.4.1/gems/bigdecimal/BigDecimal.html#ROUND_MODE) for more information.
To round to the nearest cash value in currencies without small denominations:
```ruby
Money.from_cents(11_11, "CHF").to_nearest_cash_value.format # => "CHF 11.10"
```
## Ruby on Rails
To integrate money in a Rails application use [money-rails](https://github.com/RubyMoney/money-rails).
For deprecated methods of integrating with Rails, check [the wiki](https://github.com/RubyMoney/money/wiki).
## Localization
In order to localize formatting you can use `I18n` gem:
```ruby
Money.locale_backend = :i18n
```
With this enabled a thousands separator and a decimal mark will get looked up in your `I18n` translation files. In a Rails application this may look like:
```yml
# config/locale/en.yml
en:
number:
currency:
format:
delimiter: ","
separator: "."
# falling back to
number:
format:
delimiter: ","
separator: "."
```
For this example `Money.from_cents(123456789, "SEK").format` will return `1,234,567.89
kr` which otherwise would have returned `1 234 567,89 kr`.
This will work seamlessly with [rails-i18n](https://github.com/svenfuchs/rails-i18n) gem that already has a lot of locales defined.
If you wish to disable this feature and use defaults instead:
```ruby
Money.locale_backend = nil
```
### Deprecation
The current default behaviour always checks the I18n locale first, falling back to "per currency"
localization. This is now deprecated and will be removed in favour of explicitly defined behaviour
in the next major release.
If you would like to use I18n localization (formatting depends on the locale):
```ruby
Money.locale_backend = :i18n
# example (using default localization from rails-i18n):
I18n.locale = :en
Money.from_cents(10_000_00, 'USD').format # => $10,000.00
Money.from_cents(10_000_00, 'EUR').format # => €10,000.00
I18n.locale = :es
Money.from_cents(10_000_00, 'USD').format # => $10.000,00
Money.from_cents(10_000_00, 'EUR').format # => €10.000,00
```
If you need to localize the position of the currency symbol, you
have to pass it manually. *Note: this will become the default formatting
behavior in the next version.*
```ruby
I18n.locale = :fr
format = I18n.t :format, scope: 'number.currency.format'
Money.from_cents(10_00, 'EUR').format(format: format) # => 10,00 €
```
For the legacy behaviour of "per currency" localization (formatting depends only on currency):
```ruby
Money.locale_backend = :currency
# example:
Money.from_cents(10_000_00, 'USD').format # => $10,000.00
Money.from_cents(10_000_00, 'EUR').format # => €10.000,00
```
In case you don't need localization and would like to use default values (can be redefined using
`Money.default_formatting_rules`):
```ruby
Money.locale_backend = nil
# example:
Money.from_cents(10_000_00, 'USD').format # => $10000.00
Money.from_cents(10_000_00, 'EUR').format # => €10000.00
```
## Collection
In case you're working with collections of `Money` instances, have a look at [money-collection](https://github.com/RubyMoney/money-collection)
for improved performance and accuracy.
### Troubleshooting
If you don't have some locale and don't want to get a runtime error such as:
I18n::InvalidLocale: :en is not a valid locale
Set the following:
```ruby
I18n.enforce_available_locales = false
```
## Heuristics
Prior to v6.9.0 heuristic analysis of string input was part of this gem. Since then it was extracted in to [money-heuristics gem](https://github.com/RubyMoney/money-heuristics).
## Upgrade Guides
When upgrading between major versions, please refer to the appropriate upgrade guide:
- [Upgrading to 7.0](https://github.com/RubyMoney/money/blob/main/UPGRADING-7.0.md) - Guide for migrating from 6.x to 7.0
- [Upgrading to 6.0](https://github.com/RubyMoney/money/blob/main/UPGRADING-6.0.md) - Guide for upgrading to version 6.0
These guides provide detailed information about breaking changes, new features, and step-by-step migration instructions.
|