ex_uc v1.0.3 ExUc
Elixir Unit Converter
Converts values between units.
Usage
The quickest way is the function convert
:
ExUc.convert("5 pounds", "oz") # "80.00 oz"
This is just a shortcut for the 3-steps pipeline:
import ExUc
new_val = from("5 pounds") # %ExUc.Value{unit: :lb, value: 5, kind: :mass}
|> to(:oz) # %ExUc.Value{unit: :oz, value: 80, kind: :mass}
|> as_string # "80.00 oz"
Errors
Only two errors are returned when found, both as self descriptive strings:
"undefined origin"
: Unit for the original value can’t be parsed or found in the configuration."undetermined conversion"
: Conversion between the given units can’t be determined.
Summary
Functions
Converts an structured value into a string
Converts values between units of the same kind
Parses a string into a structured value. When is not possible to get
a value from the given string, nil
will be returned. This makes the
process to fail by not being able to match a valid struct
Takes an structured value and using its kind converts it to the given unit
Functions
Converts an structured value into a string.
Parameters
- val: ExUc.Value to convert to string.
Examples
iex> ExUc.as_string(%ExUc.Value{value: 10, unit: :m})
"10.00 m"
iex> ExUc.as_string({:error, "some error"})
"some error"
Converts values between units of the same kind.
This function is a shortcut to get the string version of the converted value.
Parameters
- from_str: String with the value to convert.
- to: String or Atom with the unit to convert to.
Examples
iex>ExUc.convert("5 pounds", "oz")
"80.00 oz"
Parses a string into a structured value. When is not possible to get
a value from the given string, nil
will be returned. This makes the
process to fail by not being able to match a valid struct.
Returns %ExUc.Value{}
Parameters
- str: String containing the value and unit to convert.
Examples
iex>ExUc.from("500 mg")
%ExUc.Value{value: 500.0, unit: :mg, kind: :mass}
iex>ExUc.from("5 alien")
nil
Takes an structured value and using its kind converts it to the given unit.
Returns %ExUc.Value{}
Parameters
- val: ExUc.Value to convert.
- unit: Atom representing the unit to convert the
val
to.
Examples
iex> ExUc.to(%{value: 20, unit: :g, kind: :mass}, :mg)
%ExUc.Value{value: 20000, unit: :mg, kind: :mass}
iex> ExUc.to("15C", :K)
%ExUc.Value{value: 288.15, unit: :K, kind: :temperature}
# Errors:
iex> ExUc.to(nil, :g)
{:error, "undefined origin"}
iex> ExUc.to("10kg", :xl)
{:error, "undetermined conversion"}