Integer amounts normalized to 8 decimal places.
All amounts in Rujira are represented as non-negative integers
where 1.0 = 100_000_000 (1e8). This module provides a single entry point
new/1 that accepts any numeric input and normalizes it.
Examples
iex> Rujira.Amount.new(100)
{:ok, 100}
iex> Rujira.Amount.new("500")
{:ok, 500}
iex> Rujira.Amount.new("1000.75")
{:ok, 1000}
iex> Rujira.Amount.new(Decimal.new("1000"))
{:ok, 1000}
iex> Rujira.Amount.new("abc")
{:error, :invalid_amount}
Summary
Functions
Returns the number of decimal places (8).
Formats an 8-decimal integer amount as a human-readable string.
Creates an amount from any numeric input.
Normalizes an amount from from_decimals precision to 8 decimal places.
Returns the precision multiplier (100_000_000).
Converts an 8-decimal integer amount to a Decimal.
Types
@type t() :: non_neg_integer()
Functions
@spec decimals() :: non_neg_integer()
Returns the number of decimal places (8).
Formats an 8-decimal integer amount as a human-readable string.
Examples
iex> Rujira.Amount.format(100_000_000)
"1.00000000"
iex> Rujira.Amount.format(50_000)
"0.00050000"
@spec new(nil | integer() | String.t() | Decimal.t() | float()) :: {:ok, t() | nil} | {:error, :invalid_amount}
Creates an amount from any numeric input.
Accepts nil, integers, binary strings, Decimals, and floats.
Decimals and floats are floored to the nearest integer.
nil passes through as {:ok, nil}.
Returns {:ok, amount}, {:ok, nil}, or {:error, :invalid_amount}.
@spec normalize(integer(), non_neg_integer()) :: {:ok, t()} | {:error, :invalid_amount}
Normalizes an amount from from_decimals precision to 8 decimal places.
Examples
iex> Rujira.Amount.normalize(1_000_000, 6)
{:ok, 100_000_000}
iex> Rujira.Amount.normalize(1_000_000_000_000_000_000, 18)
{:ok, 100_000_000}
@spec precision() :: non_neg_integer()
Returns the precision multiplier (100_000_000).
Converts an 8-decimal integer amount to a Decimal.
Examples
iex> Rujira.Amount.to_decimal(100_000_000)
Decimal.new("1.00000000")