Cldr.Unit (Cldr Units v3.3.0) View Source

Supports the CLDR Units definitions which provide for the localization of many unit types.

The primary public API defines:

Link to this section Summary

Functions

Returns the base unit for a given Cldr.Unit.t() or atom().

Returns a mapping of base units to their respective unit categories.

Returns a mapping from unit categories to the base unit.

Returns a boolean indicating if two units are of the same unit category.

Decomposes a unit into subunits.

Returns the default formatting style.

Return a list of known measurement systems.

Returns a list of the known unit categories.

Returns the known units.

Localizes a unit according to the current processes locale and backend.

Localizes a unit according to a territory

Returns the default measurement system for a territory in a given category.

Returns a map of measurement systems by territory

Returns a new Unit.t struct.

Returns a new Unit.t struct or raises on error.

Convert a ratio Unit to a float unit

Returns the known styles for a unit.

Formats a number into a iolist according to a unit definition for the current process's locale and backend.

Formats a number into an iolist according to a unit definition for a locale.

Formats a number into an iolist according to a unit definition for the current process's locale and backend or raises on error.

Formats a number into an iolist according to a unit definition for the current process's locale and backend or raises on error.

Formats a number into a string according to a unit definition for the current process's locale and backend.

Formats a number into a string according to a unit definition for a locale.

Formats a number into a string according to a unit definition for the current process's locale and backend or raises on error.

Formats a number into a string according to a unit definition for the current process's locale and backend or raises on error.

Returns the units category for a given unit

Returns a mapping between Unit categories and the uses they define.

unit_type(unit) deprecated
units() deprecated

Validates a unit style and normalizes it to a standard downcased atom form

Validates a unit name and normalizes it,

Return the value of the Unit struct

Returns a new unit of the same unit type but with a zero value.

Returns a boolean indicating whether a given unit has a zero value.

Link to this section Types

Specs

conversion() ::
  Cldr.Unit.Conversion.t()
  | {[Cldr.Unit.Conversion.t(), ...], [Cldr.Unit.Conversion.t(), ...]}
  | list()

Specs

Specs

style() :: atom()

Specs

t() :: %Cldr.Unit{
  base_conversion: conversion(),
  format_options: [],
  unit: unit(),
  usage: usage(),
  value: value()
}

Specs

unit() :: atom() | String.t()

Specs

usage() :: atom()

Specs

Link to this section Functions

See Cldr.Unit.Math.add/2.

See Cldr.Unit.Math.add!/2.

Returns the base unit for a given Cldr.Unit.t() or atom().

Argument

  • unit is either a t:Cldr.Unit.t() or an atom

Returns

  • {:ok, base_unit} or

  • {:error, {exception, reason}}

Example

iex> Cldr.Unit.base_unit :square_kilometer
{:ok, :square_meter}

iex> Cldr.Unit.base_unit :square_table
{:error, {Cldr.UnknownUnitError, "Unknown unit was detected at \"table\""}}
Link to this function

base_unit_category_map()

View Source

Specs

base_unit_category_map() :: map()

Returns a mapping of base units to their respective unit categories.

Base units are a common unit for a given unit category which are used in two scenarios:

  1. When converting between units. If two units have the same base unit they can be converted to each other. See Cldr.Unit.Conversion.

  2. When identifying the preferred units for a given locale or territory, the base unit is used to aid identification of preferences for given use cases. See Cldr.Unit.Preference.

Example

=> Cldr.Unit.base_unit_category_map
%{
  "kilogram_square_meter_per_cubic_second_ampere" => :voltage,
  "kilogram_meter_per_meter_square_second" => :torque,
  "square_meter" => :area,
  "kilogram" => :mass,
  "kilogram_square_meter_per_square_second" => :energy,
  "revolution" => :angle,
  "candela_per_square_meter" => :luminance,
  ...
}

Returns a mapping from unit categories to the base unit.

See Cldr.Unit.Math.compare/2.

Link to this function

compatible?(unit_1, unit_2)

View Source

Specs

compatible?(t() | unit(), t() | unit()) :: boolean()

Returns a boolean indicating if two units are of the same unit category.

Arguments

  • unit_1 and unit_2 are any units returned by Cldr.Unit.new/2 or a valid unit name.

Returns

  • true or false

Examples

iex> Cldr.Unit.compatible? :foot, :meter
true

iex> Cldr.Unit.compatible? Cldr.Unit.new!(:foot, 23), :meter
true

iex> Cldr.Unit.compatible? :foot, :liter
false

iex> Cldr.Unit.compatible? "light_year_per_second", "meter_per_gallon"
false
Link to this function

convert(unit_1, to_unit)

View Source

See Cldr.Unit.Conversion.convert/2.

Link to this function

convert!(unit_1, to_unit)

View Source

See Cldr.Unit.Conversion.convert!/2.

Link to this function

decompose(unit, unit_list, format_options \\ [])

View Source

Specs

decompose(unit :: t(), unit_list :: [unit()], options :: Keyword.t()) :: [t()]

Decomposes a unit into subunits.

Any list compatible units can be provided however a list of units of decreasing scale is recommended. For example [:foot, :inch] or [:kilometer, :meter, :centimeter, :millimeter]

Arguments

  • unit is any unit returned by Cldr.Unit.new/2

  • unit_list is a list of valid units (one or more from the list returned by Cldr.Unit.known_units/0. All units must be from the same unit category.

  • format_options is a Keyword list of options that is added to the last unit in unit_list. The format_options will be applied when calling Cldr.Unit.to_string/3 on the unit. The default is [].

Returns

  • a list of units after decomposition or an error tuple

Examples

iex> u = Cldr.Unit.new!(10.3, :foot)
iex> Cldr.Unit.decompose u, [:foot, :inch]
[Cldr.Unit.new!(:foot, 10), Cldr.Unit.new!(:inch, Ratio.new(18, 5))]

iex> u = Cldr.Unit.new!(:centimeter, 1111)
iex> Cldr.Unit.decompose u, [:kilometer, :meter, :centimeter, :millimeter]
[Cldr.Unit.new!(:meter, 11), Cldr.Unit.new!(:centimeter, 11)]

Returns the default formatting style.

Example

iex> Cldr.Unit.default_style
:long

See Cldr.Unit.Math.div/2.

See Cldr.Unit.Math.div!/2.

Link to this function

known_measurement_systems()

View Source

Return a list of known measurement systems.

Example

iex> Cldr.Unit.known_measurement_systems()
%{
  metric: %{alias: nil, description: "Metric System"},
  uksystem: %{
    alias: :imperial,
    description: "UK System of measurement: feet, pints, etc.; pints are 20oz"
  },
  ussystem: %{
    alias: nil,
    description: "US System of measurement: feet, pints, etc.; pints are 16oz"
  }
}

Returns a list of the known unit categories.

Example

iex> Cldr.Unit.known_unit_categories
[:acceleration, :angle, :area, :compound, :concentr, :consumption, :coordinate, :digital,
 :duration, :electric, :energy, :force, :frequency, :graphics, :length, :light, :mass,
 :power, :pressure, :speed, :temperature, :torque, :volume]

Specs

known_units() :: [atom(), ...]

Returns the known units.

Known units means units that can be localised directly.

Example

=> Cldr.Unit.known_units
[:acre, :acre_foot, :ampere, :arc_minute, :arc_second, :astronomical_unit, :bit,
 :bushel, :byte, :calorie, :carat, :celsius, :centiliter, :centimeter, :century,
 :cubic_centimeter, :cubic_foot, :cubic_inch, :cubic_kilometer, :cubic_meter,
 :cubic_mile, :cubic_yard, :cup, :cup_metric, :day, :deciliter, :decimeter,
 :degree, :fahrenheit, :fathom, :fluid_ounce, :foodcalorie, :foot, :furlong,
 :g_force, :gallon, :gallon_imperial, :generic, :gigabit, :gigabyte, :gigahertz,
 :gigawatt, :gram, :hectare, :hectoliter, :hectopascal, :hertz, :horsepower,
 :hour, :inch, ...]

Localizes a unit according to the current processes locale and backend.

The curent process's locale is set with Cldr.put_locale/1.

See Cldr.Unit.localize/3 for futher details.

Link to this function

localize(unit, backend, options \\ [])

View Source

Localizes a unit according to a territory

A territory can be derived from a locale_name or Cldr.LangaugeTag.t().

Use this function if you have a unit which should be presented in a user interface using units relevant to the audience. For example, a unit #Cldr.Unit100, :meter> might be better presented to a US audiance as #Cldr.Unit328, :foot>.

Arguments

  • unit is any unit returned by Cldr.Unit.new/2

  • backend is any module that includes use Cldr and therefore is a Cldr backend module.

  • options is a keyword list of options

Options

  • :locale is any valid locale name returned by Cldr.known_locale_names/0 or a Cldr.LanguageTag struct. The default is backend.get_locale/0

  • :territory is any valid territory code returned by Cldr.known_territories/0. The default is the territory defined as part of the :locale. The option :territory has a precedence over the territory in a locale.

  • :usage is the way in which the unit is intended to be used. The available usage varyies according to the unit category. See Cldr.Unit.preferred_units/3.

Examples

iex> unit = Cldr.Unit.new!(1.83, :meter)
iex> Cldr.Unit.localize(unit, usage: :person_height, territory: :US)
[Cldr.Unit.new!(:foot, 6), Cldr.Unit.new!(:inch, Ratio.new(6485183463413016, 137269716642252725))]
Link to this function

maybe_translatable_unit(name)

View Source
Link to this function

measurement_system_for(territory, category \\ :default)

View Source

Specs

measurement_system_for(atom(), atom()) ::
  :metric | :ussystem | :uk_system | {:error, {module(), String.t()}}

Returns the default measurement system for a territory in a given category.

Arguments

  • territory is any valid territory returned by Cldr.validate_territory/1

  • category is any measurement system category. The known categories are :default, :temperature and :paper_size. The default category is :default.

Examples

iex> Cldr.Unit.measurement_system_for :US
:ussystem

iex> Cldr.Unit.measurement_system_for :GB
:uksystem

iex> Cldr.Unit.measurement_system_for :AU
:metric

iex> Cldr.Unit.measurement_system_for :US, :temperature
:ussystem

iex> Cldr.Unit.measurement_system_for :GB, :temperature
:uksystem

Specs

measurement_systems() :: map()

Returns a map of measurement systems by territory

See Cldr.Unit.Math.mult/2.

See Cldr.Unit.Math.mult!/2.

Link to this function

new(value, unit, options \\ [])

View Source

Specs

new(unit() | value(), value() | unit(), Keyword.t()) ::
  {:ok, t()} | {:error, {module(), String.t()}}

Returns a new Unit.t struct.

Arguments

Options

  • :usage is the intended use of the unit. This is used during localization to convert the unit to that appropriate for the unit category, usage, target territory and unit value. The :use must be known for the unit's category. See Cldr.Unit for more information.

Returns

  • unit or

  • {:error, {exception, message}}

Examples

iex> Cldr.Unit.new(23, :gallon)
{:ok, Cldr.Unit.new!(:gallon, 23)}

iex> Cldr.Unit.new(:gallon, 23)
{:ok, Cldr.Unit.new!(:gallon, 23)}

iex> Cldr.Unit.new(14, :gadzoots)
{:error, {Cldr.UnknownUnitError,
  "Unknown unit was detected at \"gadzoots\""}}

iex> Cldr.Unit.new(:gallon, 23, usage: :fluid)

iex> Cldr.Unit.new(:gallon, 23, usage: "fluid")
Link to this function

new!(unit, value, options \\ [])

View Source

Returns a new Unit.t struct or raises on error.

Arguments

Returns

  • unit or

  • raises an exception

Examples

iex> Cldr.Unit.new! 23, :gallon
#Cldr.Unit<:gallon, 23>

Cldr.Unit.new! 14, :gadzoots
** (Cldr.UnknownUnitError) The unit :gadzoots is not known.
    (ex_cldr_units) lib/cldr/unit.ex:57: Cldr.Unit.new!/2
Link to this function

per_pattern_for(locale_name, style, unit, backend)

View Source
Link to this function

preferred_units(unit, backend, options)

View Source

See Cldr.Unit.Preference.preferred_units/3.

Link to this function

preferred_units!(unit, backend, options)

View Source

See Cldr.Unit.Preference.preferred_units!/3.

Convert a ratio Unit to a float unit

See Cldr.Unit.Math.round/1.

See Cldr.Unit.Math.round/2.

Link to this function

round(unit, places, mode)

View Source

See Cldr.Unit.Math.round/3.

Returns the known styles for a unit.

Example

iex> Cldr.Unit.styles
[:long, :short, :narrow]

See Cldr.Unit.Math.sub/2.

See Cldr.Unit.Math.sub!/2.

Specs

to_iolist(list_or_number :: value() | t() | [t()]) ::
  {:ok, String.t()} | {:error, {atom(), binary()}}

Formats a number into a iolist according to a unit definition for the current process's locale and backend.

The curent process's locale is set with Cldr.put_locale/1.

See Cldr.Unit.to_iolist/3 for full details.

Link to this function

to_iolist(unit, backend, options \\ [])

View Source

Specs

to_iolist(value() | t(), Cldr.backend() | Keyword.t(), Keyword.t()) ::
  {:ok, list()} | {:error, {module(), binary()}}

Formats a number into an iolist according to a unit definition for a locale.

During processing any :format_options of a Unit.t() are merged with options with options taking precedence.

Arguments

  • list_or_number is any number (integer, float or Decimal) or a Cldr.Unit.t() struct or a list of Cldr.Unit.t() structs

  • backend is any module that includes use Cldr and therefore is a Cldr backend module. The default is Cldr.default_backend/0.

  • options is a keyword list of options.

Options

  • :unit is any unit returned by Cldr.Unit.known_units/0. Ignored if the number to be formatted is a Cldr.Unit.t() struct

  • :locale is any valid locale name returned by Cldr.known_locale_names/1 or a Cldr.LanguageTag struct. The default is Cldr.get_locale/0

  • :style is one of those returned by Cldr.Unit.styles. The current styles are :long, :short and :narrow. The default is style: :long

  • :list_options is a keyword list of options for formatting a list which is passed through to Cldr.List.to_string/3. This is only applicable when formatting a list of units.

  • Any other options are passed to Cldr.Number.to_string/2 which is used to format the number

Returns

  • {:ok, io_list} or

  • {:error, {exception, message}}

Examples

iex> Cldr.Unit.to_iolist Cldr.Unit.new!(:gallon, 123), MyApp.Cldr
{:ok, ["123", " gallons"]}

iex> Cldr.Unit.to_iolist 123, MyApp.Cldr, unit: :megabyte, locale: "en", style: :unknown
{:error, {Cldr.UnknownFormatError, "The unit style :unknown is not known."}}

Specs

to_iolist!(list_or_number :: value() | t() | [t()]) :: list() | no_return()

Formats a number into an iolist according to a unit definition for the current process's locale and backend or raises on error.

The curent process's locale is set with Cldr.put_locale/1.

See Cldr.Unit.to_iolist!/3 for full details.

Link to this function

to_iolist!(unit, backend, options \\ [])

View Source

Specs

to_iolist!(value() | t(), Cldr.backend() | Keyword.t(), Keyword.t()) ::
  list() | no_return()

Formats a number into an iolist according to a unit definition for the current process's locale and backend or raises on error.

During processing any :format_options of a Unit.t() are merged with options with options taking precedence.

Arguments

  • number is any number (integer, float or Decimal) or a Cldr.Unit.t() struct

  • backend is any module that includes use Cldr and therefore is a Cldr backend module. The default is Cldr.default_backend/0.

  • options is a keyword list

Options

Returns

  • io_list or

  • raises an exception

Examples

iex> Cldr.Unit.to_iolist! Cldr.Unit.new!(:gallon, 123), MyApp.Cldr
["123", " gallons"]

Specs

to_string(list_or_number :: value() | t() | [t()]) ::
  {:ok, String.t()} | {:error, {atom(), binary()}}

Formats a number into a string according to a unit definition for the current process's locale and backend.

The curent process's locale is set with Cldr.put_locale/1.

See Cldr.Unit.to_string/3 for full details.

Link to this function

to_string(list_or_unit, backend, options \\ [])

View Source

Specs

to_string(value() | t() | [t()], Cldr.backend() | Keyword.t(), Keyword.t()) ::
  {:ok, String.t()} | {:error, {atom(), binary()}}

Formats a number into a string according to a unit definition for a locale.

During processing any :format_options of a Unit.t() are merged with options with options taking precedence.

Arguments

  • list_or_number is any number (integer, float or Decimal) or a Cldr.Unit.t() struct or a list of Cldr.Unit.t() structs

  • backend is any module that includes use Cldr and therefore is a Cldr backend module. The default is Cldr.default_backend/0.

  • options is a keyword list of options.

Options

  • :unit is any unit returned by Cldr.Unit.known_units/0. Ignored if the number to be formatted is a Cldr.Unit.t() struct

  • :locale is any valid locale name returned by Cldr.known_locale_names/1 or a Cldr.LanguageTag struct. The default is Cldr.get_locale/0

  • :style is one of those returned by Cldr.Unit.styles. The current styles are :long, :short and :narrow. The default is style: :long

  • :list_options is a keyword list of options for formatting a list which is passed through to Cldr.List.to_string/3. This is only applicable when formatting a list of units.

  • Any other options are passed to Cldr.Number.to_string/2 which is used to format the number

Returns

  • {:ok, formatted_string} or

  • {:error, {exception, message}}

Examples

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 123), MyApp.Cldr
{:ok, "123 gallons"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 1), MyApp.Cldr
{:ok, "1 gallon"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 1), MyApp.Cldr, locale: "af"
{:ok, "1 gelling"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 1), MyApp.Cldr, locale: "bs"
{:ok, "1 galon"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 1234), MyApp.Cldr, format: :long
{:ok, "1 thousand gallons"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:gallon, 1234), MyApp.Cldr, format: :short
{:ok, "1K gallons"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:megahertz, 1234), MyApp.Cldr
{:ok, "1,234 megahertz"}

iex> Cldr.Unit.to_string Cldr.Unit.new!(:megahertz, 1234), MyApp.Cldr, style: :narrow
{:ok, "1,234MHz"}

iex> unit = Cldr.Unit.new!(123, :foot)
iex> Cldr.Unit.to_string unit, MyApp.Cldr
{:ok, "123 feet"}

iex> Cldr.Unit.to_string 123, MyApp.Cldr, unit: :foot
{:ok, "123 feet"}

iex> Cldr.Unit.to_string Decimal.new(123), MyApp.Cldr, unit: :foot
{:ok, "123 feet"}

iex> Cldr.Unit.to_string 123, MyApp.Cldr, unit: :megabyte, locale: "en", style: :unknown
{:error, {Cldr.UnknownFormatError, "The unit style :unknown is not known."}}

Specs

to_string!(list_or_number :: value() | t() | [t()]) :: String.t() | no_return()

Formats a number into a string according to a unit definition for the current process's locale and backend or raises on error.

The curent process's locale is set with Cldr.put_locale/1.

See Cldr.Unit.to_string!/3 for full details.

Link to this function

to_string!(unit, backend, options \\ [])

View Source

Specs

to_string!(value() | t() | [t()], Cldr.backend() | Keyword.t(), Keyword.t()) ::
  String.t() | no_return()

Formats a number into a string according to a unit definition for the current process's locale and backend or raises on error.

During processing any :format_options of a Unit.t() are merged with options with options taking precedence.

Arguments

  • number is any number (integer, float or Decimal) or a Cldr.Unit.t() struct

  • backend is any module that includes use Cldr and therefore is a Cldr backend module. The default is Cldr.default_backend/0.

  • options is a keyword list

Options

Returns

  • formatted_string or

  • raises an exception

Examples

iex> Cldr.Unit.to_string! Cldr.Unit.new!(:gallon, 123), MyApp.Cldr
"123 gallons"

iex> Cldr.Unit.to_string! Cldr.Unit.new!(:gallon, 1), MyApp.Cldr
"1 gallon"

iex> Cldr.Unit.to_string! Cldr.Unit.new!(:gallon, 1), MyApp.Cldr, locale: "af"
"1 gelling"
This function is deprecated. Use `Cldr.Unit.known_unit_categories/0.

See Cldr.Unit.known_unit_categories/0.

Specs

unit_category(t() | String.t() | atom()) ::
  {:ok, atom()} | {:error, {module(), String.t()}}

Returns the units category for a given unit

Options

Returns

  • {:ok, category} or

  • {:error, {exception, message}}

Examples

iex> Cldr.Unit.unit_category :pint_metric
{:ok, :volume}

iex> Cldr.Unit.unit_category :stone
{:ok, :mass}

Returns a mapping between Unit categories and the uses they define.

Link to this function

unit_not_translatable_error(unit)

View Source
This function is deprecated. Please use `Cldr.Unit.unit_category/1.
This function is deprecated. Use Cldr.Unit.known_units/0.
Link to this function

unknown_base_unit_error(unit_name)

View Source

Validates a unit style and normalizes it to a standard downcased atom form

Link to this function

validate_unit(unit_name)

View Source

Validates a unit name and normalizes it,

A unit name can be expressed as:

  • an atom() in which case the unit must be localizable in CLDR directly

  • or a String.t() in which case it is parsed into a list of composable subunits that can be converted but are not guaranteed to be output as a localized string.

Arguments

  • unit_name is an atom() or String.t(), supplied as is or as part of an Cldr.Unit.t() struct.

Returns

  • {:ok, canonical_unit_name, conversion} where canonical_unit_name is the normalized unit name and conversion is an opaque structure used to convert this this unit into its base unit or

  • {:error, {exception, reason}}

Notes

A returned unit_name that is an atom is directly localisable (CLDR has translation data for the unit).

A unit_name that is a String.t() is composed of one or more unit names that need to be resolved in order for the unit_name to be localised.

The difference is an implementation detail and should not be of concern to the user of this library.

Examples

iex> Cldr.Unit.validate_unit :meter
{
  :ok,
  :meter,
  [meter: %Cldr.Unit.Conversion{base_unit: [:meter], factor: 1, offset: 0}]
}

iex> Cldr.Unit.validate_unit "meter"
{:ok, :meter,
 [meter: %Cldr.Unit.Conversion{base_unit: [:meter], factor: 1, offset: 0}]}

iex> Cldr.Unit.validate_unit "miles_per_liter"
{:error, {Cldr.UnknownUnitError, "Unknown unit was detected at \"s\""}}

iex> Cldr.Unit.validate_unit "mile_per_liter"
{:ok, "mile_per_liter",
 {[
    mile:
     %Cldr.Unit.Conversion{
       base_unit: [:meter],
       factor: Ratio.new(905980129838867985, 562949953421312),
       offset: 0
     }
  ],
  [
    liter:
     %Cldr.Unit.Conversion{
       base_unit: [:cubic_meter],
       factor: Ratio.new(1152921504606847, 1152921504606846976),
       offset: 0
     }
  ]}}

Specs

value(unit :: t()) :: value()

Return the value of the Unit struct

Arguments

Returns

  • an integer, float or Decimal representing the amount of the unit

Example

iex> Cldr.Unit.value Cldr.Unit.new!(:kilogram, 23)
23

Returns a new unit of the same unit type but with a zero value.

Argument

Example

iex> u = Cldr.Unit.new!(:foot, 23.3)
#Cldr.Unit<:foot, 23.3>
iex> Cldr.Unit.zero(u)
#Cldr.Unit<:foot, 0.0>

Returns a boolean indicating whether a given unit has a zero value.

Argument

Examples

iex> u = Cldr.Unit.new!(:foot, 23.3)
#Cldr.Unit<:foot, 23.3>
iex> Cldr.Unit.zero?(u)
false

iex> u = Cldr.Unit.new!(:foot, 0)
#Cldr.Unit<:foot, 0>
iex> Cldr.Unit.zero?(u)
true