Utility functions to work with numeric types.
Summary
Functions
Checks whether a value is an integer, float, or decimal.
Checks whether a value is a positive integer.
Parse a string or another numeric type to decimal.
Same as to_decimal/1 but raises when unable to parse.
Parse a string or another numeric type to a float.
Same as to_float/1 but raises when unable to parse.
Parse a string or another numeric type to an integer.
Same as to_integer/1 but raises when unable to parse.
Truncates a numeric value and returns an integer.
Types
Functions
Checks whether a value is an integer, float, or decimal.
You need to import or require this module to use this guard.
Examples
iex> is_numeric(12)
true
iex> is_numeric(Decimal.new("12.5"))
true
iex> is_numeric("12.5")
false
Checks whether a value is a positive integer.
You need to import or require this module to use this guard.
Examples
iex> is_positive(12)
true
iex> is_positive(0)
false
iex> is_positive(1.5)
false
Parse a string or another numeric type to decimal.
If the input is nil or invalid string, returns nil.
Also see to_decimal!/1.
Examples
iex> ExUtils.Numbers.to_decimal(" 12.5 ")
Decimal.new("12.5")
iex> ExUtils.Numbers.to_decimal(12)
Decimal.new("12")
iex> ExUtils.Numbers.to_decimal("invalid")
nil
Same as to_decimal/1 but raises when unable to parse.
Examples
iex> ExUtils.Numbers.to_decimal!("12.5")
Decimal.new("12.5")
iex> ExUtils.Numbers.to_decimal!("invalid")
** (ArgumentError) unable to parse "invalid"
Parse a string or another numeric type to a float.
If the input is nil or invalid string, returns nil.
Also see to_float!/1.
Examples
iex> ExUtils.Numbers.to_float(" 12.5 ")
12.5
iex> ExUtils.Numbers.to_float(12)
12.0
iex> ExUtils.Numbers.to_float("invalid")
nil
Same as to_float/1 but raises when unable to parse.
Examples
iex> ExUtils.Numbers.to_float!("12.5")
12.5
iex> ExUtils.Numbers.to_float!("invalid")
** (ArgumentError) unable to parse "invalid"
Parse a string or another numeric type to an integer.
If the input is a decimal or float, it rounds it. If the input is nil or invalid string, returns nil.
Also see to_integer!/1.
Examples
iex> ExUtils.Numbers.to_integer(Decimal.new("12.5"))
13
iex> ExUtils.Numbers.to_integer(12.4)
12
iex> ExUtils.Numbers.to_integer("12")
12
iex> ExUtils.Numbers.to_integer("12.5")
nil
Same as to_integer/1 but raises when unable to parse.
Examples
iex> ExUtils.Numbers.to_integer!("12")
12
iex> ExUtils.Numbers.to_integer!("12.5")
** (ArgumentError) unable to parse "12.5"
Truncates a numeric value and returns an integer.
Examples
iex> ExUtils.Numbers.trunc(Decimal.new("5.7"))
5
iex> ExUtils.Numbers.trunc(-5.7)
-5
iex> ExUtils.Numbers.trunc(5)
5