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
Converts a numeric value from one unit to another.
Converts a numeric value from one unit to another, raising on error.
Checks whether two units are convertible (same dimensional base unit).
Functions
@spec convert(number(), String.t(), String.t()) :: {:ok, float()} | {: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
valueis the numeric value to convert (integer, float, or Decimal).fromis the source unit identifier string.tois 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}
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
valueis the numeric value to convert.fromis the source unit identifier string.tois the target unit identifier string.
Returns
- The converted value as a float.
Examples
iex> Localize.Unit.Conversion.convert!(1000, "meter", "kilometer")
1.0
Checks whether two units are convertible (same dimensional base unit).
Arguments
unit_1is a unit identifier string or parsed AST.unit_2is a unit identifier string or parsed AST.
Returns
trueif the units are convertible,falseotherwise.
Examples
iex> Localize.Unit.Conversion.convertible?("foot", "meter")
true
iex> Localize.Unit.Conversion.convertible?("foot", "kilogram")
false