elixirmoney/money
{ "createdAt": "2015-08-26T15:02:28Z", "defaultBranch": "master", "description": "Elixir library for working with Money safer, easier, and fun... Is an interpretation of the Fowler's Money pattern in fun.prog.", "fullName": "elixirmoney/money", "homepage": "https://hex.pm/packages/money/", "language": "Elixir", "name": "money", "pushedAt": "2025-07-27T13:10:50Z", "stargazersCount": 844, "topics": [], "updatedAt": "2025-11-12T17:50:57Z", "url": "https://github.com/elixirmoney/money"}Elixir library for working with Money safer, easier, and fun, is an interpretation of the Martin Fowler’s Money pattern in functional programming.
“If I had a dime for every time I’ve seen someone use FLOAT to store currency, I’d have $999.997634” — Bill Karwin
In short: You shouldn’t represent monetary values by a float. Wherever
you need to represent money, use Money.
Installation
Section titled “Installation”Money comes with no required dependencies.
Add the following to your mix.exs:
def deps do [{:money, "~> 1.14"}]endthen run mix deps.get.
five_eur = Money.new(500, :EUR) # %Money{amount: 500, currency: :EUR}ten_eur = Money.add(five_eur, five_eur) # %Money{amount: 10_00, currency: :EUR}hundred_eur = Money.multiply(ten_eur, 10) # %Money{amount: 100_00, currency: :EUR}ninety_nine_eur = Money.subtract(hundred_eur, 100) # %Money{amount: 99_00, currency: :EUR}shares = Money.divide(ninety_nine_eur, 2) # [%Money{amount: 4950, currency: :EUR}, %Money{amount: 4950, currency: :EUR}]
Money.equals?(five_eur, Money.new(500, :EUR)) # trueMoney.zero?(five_eur); # falseMoney.positive?(five_eur); # true
Money.Currency.symbol(:USD) # $Money.Currency.symbol(Money.new(500, :AFN)) # ؋Money.Currency.name(Money.new(500, :AFN)) # Afghani
Money.to_string(Money.new(500, :CNY)) # ¥ 5.00Money.to_string(Money.new(1_234_56, :EUR), separator: ".", delimiter: ",", symbol: false)"1.234,56"Money.to_string(Money.new(1_234_56, :USD), fractional_unit: false) # "$1,234"Money.to_string(Money.new(1_234_50, :USD), strip_insignificant_zeros: true) # "$1,234.5"Serialization to database with single currency
Section titled “Serialization to database with single currency”Bring Money to your Ecto project.
The underlying database type is integer
-
Set a default currency in
config.ex:config :money,default_currency: :USD -
Create migration with integer type:
create table(:jobs) doadd :amount, :integerend -
Create schema using the
Money.Ecto.Amount.TypeEcto type (don’t forget runmix ecto.migrate):schema "jobs" dofield :amount, Money.Ecto.Amount.Typeend -
Save to the database:
iex(1)> Repo.insert %Job{amount: Money.new(100, :USD)}[debug] QUERY OK db=90.7ms queue=0.1msINSERT INTO "jobs" ("amount","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" [100, {{2019, 2, 12}, {7, 29, 8, 589489}}, {{2019, 2, 12}, {7, 29, 8, 593185}}]{:ok,%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,amount: %Money{amount: 100, currency: :USD},id: 1,inserted_at: ~N[2019-02-12 07:29:08.589489],updated_at: ~N[2019-02-12 07:29:08.593185]}} -
Get from the database:
iex(2)> Repo.one(Job, limit: 1)[debug] QUERY OK source="jobs" db=1.8msSELECT j0."id", j0."amount", j0."inserted_at", j0."updated_at" FROM "jobs" AS j0 []%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,amount: %Money{amount: 100, currency: :USD},id: 1,inserted_at: ~N[2019-02-12 07:29:08.589489],updated_at: ~N[2019-02-12 07:29:08.593185]}
Serialization to PostgreSQL with multiple currency
Section titled “Serialization to PostgreSQL with multiple currency”Money.Ecto.Composite.Type Ecto type represents serialization of Money.t to PostgreSQL Composite Types with saving currency.
-
Create migration with custom type:
def up doexecute """CREATE TYPE public.money_with_currency AS (amount integer, currency varchar(3))"""enddef down doexecute """DROP TYPE public.money_with_currency"""end -
Then use created custom type(
money_with_currency) for money field:def change doalter table(:jobs) doadd :price, :money_with_currencyendend -
Create schema using the
Money.Ecto.Composite.TypeEcto type (don’t forget runmix ecto.migrate):schema "jobs" dofield :price, Money.Ecto.Composite.Typeend -
Save to the database:
iex(1)> Repo.insert %Job{price: Money.new(100, :JPY)}[debug] QUERY OK db=7.7msINSERT INTO "jobs" ("price","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" [{100, "JPY"}, {{2019, 2, 12}, {8, 7, 44, 729114}}, {{2019, 2, 12}, {8, 7, 44, 729124}}]{:ok,%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,id: 6,inserted_at: ~N[2019-02-12 08:07:44.729114],price: %Money{amount: 100, currency: :JPY},updated_at: ~N[2019-02-12 08:07:44.729124]}} -
Get from the database:
iex(2)> Repo.one(Job, limit: 1)[debug] QUERY OK source="jobs" db=1.4msSELECT j0."id", j0."price", j0."inserted_at", j0."updated_at" FROM "jobs" AS j0 []%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,id: 6,inserted_at: ~N[2019-02-12 08:07:44.729114],price: %Money{amount: 100, currency: :JPY},updated_at: ~N[2019-02-12 08:07:44.729124]}
Serialization to database (JSON) with multiple currency
Section titled “Serialization to database (JSON) with multiple currency”Money.Ecto.Map.Type Ecto type represents serialization of Money.t to map(JSON) with saving currency.
-
Create migration with map type:
def change doalter table(:jobs) doadd :price, :mapendend -
Create schema using the
Money.Ecto.Map.TypeEcto type (don’t forget runmix ecto.migrate):schema "jobs" dofield :price, Money.Ecto.Map.Typeend -
Save to the database:
iex(1)> Repo.insert %Job{price: Money.new(100, :JPY)}[debug] QUERY OK db=4.6msINSERT INTO "jobs" ("price","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" [%{"amount" => 100, "currency" => "JPY"}, {{2019, 2, 26}, {9, 40, 14, 381721}}, {{2019, 2, 26}, {9, 40, 14, 381730}}]{:ok,%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,id: 9,inserted_at: ~N[2019-02-26 09:40:14.381721],price: %Money{amount: 100, currency: :JPY},updated_at: ~N[2019-02-26 09:40:14.381730]}} -
Get from the database:
iex(8)> Repo.one(Job, limit: 1)[debug] QUERY OK source="jobs" db=2.0msSELECT j0."id", j0."price", j0."inserted_at", j0."updated_at" FROM "jobs" AS j0 []%MoneyTest.Offers.Job{__meta__: #Ecto.Schema.Metadata<:loaded, "jobs">,id: 10,inserted_at: ~N[2019-02-26 09:40:45.205076],price: %Money{amount: 100, currency: :JPY},updated_at: ~N[2019-02-26 09:40:45.205084]}
Money.Sigils
Section titled “Money.Sigils”# Sigils for Moneyimport Money.Sigils
iex> ~M[1000]USD%Money{amount: 1000, currency: :USD}
# If you have a default currency configured (e.g. to GBP), you can doiex> ~M[1000]%Money{amount: 1000, currency: :GBP}Money.Currency
Section titled “Money.Currency”# Currency convenience methodsimport Money.Currency, only: [usd: 1, eur: 1, afn: 1]
iex> usd(100_00)%Money{amount: 10000, currency: :USD}iex> eur(100_00)%Money{amount: 10000, currency: :EUR}iex> afn(100_00)%Money{amount: 10000, currency: :AFN}
Money.Currency.symbol(:USD) # $Money.Currency.symbol(afn(500)) # ؋Money.Currency.name(afn(500)) # AfghaniMoney.Currency.get(:AFN) # %{name: "Afghani", symbol: "؋"}Phoenix.HTML.Safe
Section titled “Phoenix.HTML.Safe”Bring Money to your Phoenix project.
If you are using Phoenix, you can include money objects directly into your output and they will be correctly escaped.
<b><%= Money.new(12345,67, :GBP) %></b>Configuration
Section titled “Configuration”You can set a default currency and default formatting preferences as follows:
config :money, default_currency: :EUR, separator: ".", delimiter: ",", symbol: false, symbol_on_right: false, symbol_space: false, fractional_unit: true, strip_insignificant_zeros: false, code: false, minus_sign_first: true, strip_insignificant_fractional_unit: falseThen you don’t have to specify the currency.
iex> amount = Money.new(1_234_50)%Money{amount: 123450, currency: :EUR}iex> to_string(amount)"1.234,50"Here is another example of formatting money:
iex> amount = Money.new(1_234_50)%Money{amount: 123450, currency: :EUR}iex> Money.to_string(amount, symbol: true, symbol_on_right: true, symbol_space: true)"1.234,50 €"Custom Currencies
Section titled “Custom Currencies”In some cases we can need to add not common currencies, like crypto currencies or others. In order to add your own currencies you have to add them in the config file following this format:
config :money, custom_currencies: [ BTC: %{name: "Bitcoin", symbol: "₿", exponent: 8}, GCS: %{name: "Galactic Credit Standard", symbol: "gcs", exponent: 0} ]Custom Currencies Display Options
Section titled “Custom Currencies Display Options”In some cases, we may need to display the currency in a different way than the default format. For example, we may want to display the currency symbol on the right side of the amount for some currencies. To achieve this, you can add the following configuration:
config :money, custom_display_options: [ EUR: %{symbol_on_right: true, symbol_space: true, separator: ".", delimiter: ",", symbol: true}, JPY: %{symbol_on_right: true, separator: ".", delimiter: ",", symbol: true} ]Troubleshooting
Section titled “Troubleshooting”Validating amount in Ecto changeset
Section titled “Validating amount in Ecto changeset”When using the Money.Ecto.Amount.Type type, it may seem that a simple value validation should work, for example:
schema "jobs" do field :amount, Money.Ecto.Amount.Typeend
def changeset(struct, params \\ %{}) do struct |> cast(params, [:amount]) |> validate_number(:amount, [greater_than: 0])endBut this kind of validation will not work, since under the hood Money.Ecto.Amount.Type has the structure %Money{amount: ..., currency: ...}. To validate the data in this case, we recommend adding custom validation that matches your logic.
Example:
def changeset(struct, params \\ %{}) do struct |> cast(params, [:amount]) |> validate_money(:amount)end
defp validate_money(changeset, field) do validate_change(changeset, field, fn _, %Money{amount: amount} when amount > 0 -> [] _, _ -> [amount: "must be greater than 0"] end)endLack of precision when using Money.parse
Section titled “Lack of precision when using Money.parse”Sometimes you need to work with large numbers (for example, cryptocurrencies) and Float precision is not enough. In this case it is better to use Decimal package. Money already has support for Decimal and you just need to add it to your project dependencies.
License
Section titled “License”MIT License please see the [LICENSE.md]!(./LICENSE.md) file.