ExUc - Elixir Unit Converter

Converts values between units.

Installation

From Hex, the package can be installed as:

  1. Add ex_uc to your list of dependencies in mix.exs:
```elixir
def deps do
  [{:ex_uc, "~> 1.0"}]
end
```
  1. Ensure ex_uc is started before your application:
```elixir
def application do
  [applications: [:ex_uc]]
end
```

Requirements

This package requires Elixir 1.3+

Usage

The quickest way is the function convert:

iex>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"

The same unit can be identified by several aliases:

convert("5 km", "miles") # "3.11 miles"
convert("5 kms", "mi") # "3.11 mi"
convert("5 kilometers", "mile") # "3.11 mile"
convert("5km", "mile") # "3.11 mile"

Errors

Only two errors are returned when found, both as self descriptive strings:

Configuration

The only configurable variable is precision, by default 2. It determines how many decimals will have the result when is converted into string. Just define it on your config files as:

config :ex_uc, precision: 2

Units

Included are some of the most frequent units grouped by kinds:

Adding More Units

Kinds are really easy to extend. You don't need to add a conversion to every other existent unit in the kind (though, of course you can). ExUc will find the shortest path in a kind of units as a graph, using defined conversions.

New unit types (kinds) can be defined using configuration options for :ex_uc application. Each unit must have definitions for units and conversions fallowing this structure:

use Mix.Config

config :ex_uc, :<KIND>_units,
  <UNIT>: ["alias 1", "alias 2", "alias N"], # List with every alias intended to relate to unit identified by UNIT

config :ex_uc, :<KIND>_conversions,
  <UNIT_A>_to_<UNIT_B>: 0.001,      # Multiplication factor
  <UNIT_C>_to_<UNIT_D>: &(&1 + 5)   # Conversion formula.
  <UNIT_X>_to_<UNIT_Y>: :special    # Atom referencing a special method.  

Which have two sections:

Better Unit Conversions

PRs or Issues with new units or more accurate conversions are welcome.

Documentation

Detailed documentation can be found at hex docs.

Note

This project was inspired by the awesome Ruby gem by Kevin C. Olbrich, Ph.D.

License

MIT