ex_uc v0.1.5-dev ExUc
Elixir Unit Converter
Converts values with units within the same kind.
It could be used as:
value = ExUc.from("5' 2\"")
|> ExUc.to(:m)
|> ExUc.as_string
Or:
import ExUc
from("25C") |> to(:F) |> as_string # "77 F"
Or simply:
"#{ExUc.to("72F", :K)}" # "295.37 K"
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 stringify.
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 unito 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"}