Packages

A currency converter backed by the Brazilian Central Bank (BCB) PTAX closing rates.

Retired package: Release invalid - Exchange rate calculations are incorrect

Current section

Files

Jump to
ptax lib ptax.ex
Raw

lib/ptax.ex

defmodule PTAX do
@moduledoc """
Converts between currencies using the Brazilian Central Bank's PTAX rates.
"""
@doc """
Exchanges a `Money` amount to the given currency using PTAX rates.
Defaults to the latest known rates. Pass a `Date` to use historic rates for that date.
Returns `{:ok, Money.t()}` on success, or `{:error, reason}` if the rates
are unavailable or the currency is not supported.
## Examples
iex> PTAX.exchange(Money.new!(:GBP, "50"), :BRL, ~D[2026-05-15])
{:ok, Money.new!(:BRL, "7.41")}
"""
@spec exchange(Money.t(), Money.currency_reference()) ::
{:ok, Money.t()} | {:error, {module(), binary()}}
def exchange(%Money{} = money, currency) do
with {:ok, money} <- Money.to_currency(money, currency) do
{:ok, Money.round(money, currency_digits: :cash)}
end
end
@spec exchange(Money.t(), Money.currency_reference(), Date.t()) ::
{:ok, Money.t()} | {:error, {module(), binary()}}
def exchange(%Money{} = money, currency, date) do
rates = Money.ExchangeRates.historic_rates(date)
with {:ok, money} <- Money.to_currency(money, currency, rates) do
{:ok, Money.round(money, currency_digits: :cash)}
end
end
end