Search documentation of Localize

# Localize.Utils.Decimal (Localize v0.39.0)

Copy Markdown View Source

Compatibility layer for `Decimal` library operations.

Provides normalized function signatures for common `Decimal` operations used throughout Localize.

## Summary

### Functions

compare(decimal_1, decimal_2)

Compares two `Decimal` values.

parse(string)

Parses a string into a `Decimal` value.

reduce(decimal)

Normalizes a `Decimal` value by removing trailing zeros from the coefficient.

## Functions

# compare(decimal_1, decimal_2)

    @spec compare(Decimal.t(), Decimal.t()) :: :eq | :lt | :gt

Compares two `Decimal` values.

### Arguments

- `decimal_1` — a `Decimal.t()` value.

- `decimal_2` — a `Decimal.t()` value.

### Returns

- `:lt` if `decimal_1` is less than `decimal_2`.

- `:eq` if they are equal.

- `:gt` if `decimal_1` is greater than `decimal_2`.

### Examples

    iex> Localize.Utils.Decimal.compare(Decimal.new("1.0"), Decimal.new("2.0"))
    :lt

# parse(string)

    @spec parse(String.t()) :: {Decimal.t(), String.t()} | {:error, String.t()}

Parses a string into a `Decimal` value.

### Arguments

- `string` — a string representation of a number.

### Returns

- `{decimal, ""}` if the string was successfully parsed.

- `{:error, string}` if the string could not be parsed.

### Examples

    iex> Localize.Utils.Decimal.parse("3.14")
    {Decimal.new("3.14"), ""}

    iex> Localize.Utils.Decimal.parse("not_a_number")
    {:error, "not_a_number"}

# reduce(decimal)

    @spec reduce(Decimal.t()) :: Decimal.t()

Normalizes a `Decimal` value by removing trailing zeros from the coefficient.

### Arguments

- `decimal` — a `Decimal.t()` value to normalize.

### Returns

- A normalized `Decimal.t()`.

### Examples

    iex> Localize.Utils.Decimal.reduce(Decimal.new("1.20"))
    Decimal.new("1.2")