Search documentation of Localize

# Localize.Unit.Conversion (Localize v0.39.0)

Copy Markdown View Source

Converts numeric values between CLDR units of measure.

Two units are convertible if they reduce to the same base unit. The conversion goes through the base unit: `source_value → base_value → target_value`.

For simple units: `base_value = source_value * factor + offset`. For compound units (products and per-expressions), the total factor is the product of all component factors raised to their respective powers.

## Summary

### Functions

convert(value, from, to)

Converts a numeric value from one unit to another.

convert!(value, from, to)

Converts a numeric value from one unit to another, raising on error.

convertible?(unit_1, unit_2)

Checks whether two units are convertible (same dimensional base unit).

## Functions

# convert(value, from, to)

    @spec convert(number() | Decimal.t(), String.t(), String.t()) ::
      {:ok, float() | Decimal.t()} | {:error, Exception.t() | String.t()}

Converts a numeric value from one unit to another.

Both units must be of the same category (convertible). Accepts integers, floats, and Decimal values.

### Arguments

- `value` is the numeric value to convert (integer, float, or Decimal).

- `from` is the source unit identifier string.

- `to` is the target unit identifier string.

### Returns

- `{:ok, converted_value}` where the result is a float, or

- `{:error, reason}` if the units cannot be parsed or are not convertible.

### Examples

    iex> Localize.Unit.Conversion.convert(1, "kilometer", "meter")
    {:ok, 1000.0}

    iex> Localize.Unit.Conversion.convert(32, "fahrenheit", "celsius")
    {:ok, 0.0}

# convert!(value, from, to)

    @spec convert!(number() | Decimal.t(), String.t(), String.t()) ::
      float() | Decimal.t() | no_return()

Converts a numeric value from one unit to another, raising on error.

Same as `convert/3` but returns the value directly or raises `ArgumentError`.

### Arguments

- `value` is the numeric value to convert.

- `from` is the source unit identifier string.

- `to` is the target unit identifier string.

### Returns

- The converted value as a float.

### Examples

    iex> Localize.Unit.Conversion.convert!(1000, "meter", "kilometer")
    1.0

# convertible?(unit_1, unit_2)

    @spec convertible?(String.t() | tuple(), String.t() | tuple()) :: boolean()

Checks whether two units are convertible (same dimensional base unit).

### Arguments

- `unit_1` is a unit identifier string or parsed AST.

- `unit_2` is a unit identifier string or parsed AST.

### Returns

- `true` if the units are convertible, `false` otherwise.

### Examples

    iex> Localize.Unit.Conversion.convertible?("foot", "meter")
    true

    iex> Localize.Unit.Conversion.convertible?("foot", "kilogram")
    false