NumberF.CustomFormatter (NumberF v0.3.0)

Copy Markdown View Source

Custom implementations for number formatting functions. Replaces functionality from the 'number' dependency.

Summary

Functions

Formats a number as currency with specified unit and precision.

Formats a number with delimiters for thousands and decimal separator.

Sums a list of Decimal values, flattening any nesting.

Converts a string to a boolean.

Converts a value to a Decimal.

Converts a value to a float.

Converts a value to an integer.

Functions

number_to_currency(number, opts \\ [])

Formats a number as currency with specified unit and precision.

Examples

iex> NumberF.CustomFormatter.number_to_currency(1234.56, unit: "USD", precision: 2)
"USD 1,234.56"

iex> NumberF.CustomFormatter.number_to_currency("1234.56", unit: "USD", precision: 2)
"USD 1,234.56"

number_to_delimited(number, opts \\ [])

Formats a number with delimiters for thousands and decimal separator.

Examples

iex> NumberF.CustomFormatter.number_to_delimited(1234567.89, delimiter: ",", separator: ".", precision: 2)
"1,234,567.89"

iex> NumberF.CustomFormatter.number_to_delimited("1234567.89", delimiter: ",", separator: ".", precision: 2)
"1,234,567.89"

sum_decimal(list)

Sums a list of Decimal values, flattening any nesting.

Examples

iex> NumberF.CustomFormatter.sum_decimal([Decimal.new("1.10"), Decimal.new("2.20")])
Decimal.new("3.30")

to_boolean(value)

Converts a string to a boolean.

Recognises "true"/"yes"/"on" and "false"/"no"/"off", case-insensitively. Anything else raises rather than guessing.

Examples

iex> NumberF.CustomFormatter.to_boolean("YES")
true

iex> NumberF.CustomFormatter.to_boolean("off")
false

to_decimal(value)

Converts a value to a Decimal.

Examples

iex> NumberF.CustomFormatter.to_decimal("123.45")
Decimal.new("123.45")

iex> NumberF.CustomFormatter.to_decimal(123)
Decimal.new("123")

to_float(value)

Converts a value to a float.

Examples

iex> NumberF.CustomFormatter.to_float("123.45")
123.45

iex> NumberF.CustomFormatter.to_float(123)
123.0

to_int(value)

Converts a value to an integer.

Edge cases

Accepts integers unchanged. Guarding this was not academic: the previous implementation called Integer.parse/1 unguarded, so it raised on the very type it returns. Floats are truncated toward zero, matching trunc/1.

Examples

iex> NumberF.CustomFormatter.to_int("123.45")
123

iex> NumberF.CustomFormatter.to_int(12)
12

iex> NumberF.CustomFormatter.to_int(3.9)
3