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.
Money comes with no required dependencies.
Add the following to your mix.exs:
defdepsdo[{:money,"~> 1.12"}]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);# trueMoney.Currency.symbol(:USD)# $Money.Currency.symbol(Money.new(500,:AFN))# ؋Money.Currency.name(Money.new(500,:AFN))# AfghaniMoney.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"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:
createtable(: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]}
Money.Ecto.Composite.Type Ecto type represents serialization of Money.t to PostgreSQL Composite Types with saving currency.
Create migration with custom type:
defupdoexecute""" CREATE TYPE public.money_with_currency AS (amount integer, currency varchar(3)) """enddefdowndoexecute""" DROP TYPE public.money_with_currency """end
Then use created custom type(
money_with_currency) for money field:defchangedoaltertable(: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]}
Money.Ecto.Map.Type Ecto type represents serialization of Money.t to map(JSON) with saving currency.
Create migration with map type:
defchangedoaltertable(: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]}
# Sigils for MoneyimportMoney.Sigilsiex>~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}# Currency convenience methodsimportMoney.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: "؋"}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>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 €"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}]When using the Money.Ecto.Amount.Type type, it may seem that a simple value validation should work, for example:
schema"jobs"dofield:amount,Money.Ecto.Amount.Typeenddefchangeset(struct,params\\%{})dostruct|>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:
defchangeset(struct,params\\%{})dostruct|>cast(params,[:amount])|>validate_money(:amount)enddefpvalidate_money(changeset,field)dovalidate_change(changeset,field,fn_,%Money{amount: amount}whenamount>0->[]_,_->[amount: "must be greater than 0"]end)endSometimes 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.
MIT License please see the LICENSE.md file.