A2UICore.Coerce (A2UICore v0.1.1)

Copy Markdown View Source

Value coercions shared by the catalog functions: truthiness, text and number conversion.

The rules follow the reference engines so that a function evaluates to the same result everywhere:

  • truthy?/1 is Python's bool(): nil, false, 0, 0.0, "", [] and %{} are falsy, everything else is truthy.
  • to_string/1 renders a value the way formatString interpolates it: nil is empty, booleans are true/false, objects and arrays are compact JSON, numbers use the shortest round-trip form.
  • to_float/1 and to_integer/1 accept numbers, booleans and numeric strings. The BEAM has no infinity or NaN, so "inf" and "nan" are not numbers here.

Examples

iex> A2UICore.Coerce.truthy?(%{})
false
iex> A2UICore.Coerce.to_string([1, "a"])
"[1,\"a\"]"
iex> A2UICore.Coerce.to_float(" 42.5 ")
{:ok, 42.5}

Summary

Functions

Splits a float into {sign, coefficient, exponent} with value = ±coefficient × 10^exponent using its shortest round-trip decimal representation. sign is "-" or "" (negative zero keeps its sign).

Python's repr of a float: the shortest round-trip digits, 1e+16 style exponents from 1e16, and plain notation down to 1e-4.

Converts a value to a float, as Python's float() does.

Converts a value to an integer, as Python's int() does: floats truncate toward zero, booleans are 0/1, strings must be integer literals.

Renders a value as interpolated text.

Python truthiness of a decoded JSON value.

Functions

decompose(value)

(since 0.1.0)
@spec decompose(float()) :: {String.t(), non_neg_integer(), integer()}

Splits a float into {sign, coefficient, exponent} with value = ±coefficient × 10^exponent using its shortest round-trip decimal representation. sign is "-" or "" (negative zero keeps its sign).

float_to_string(value)

(since 0.1.0)
@spec float_to_string(float()) :: String.t()

Python's repr of a float: the shortest round-trip digits, 1e+16 style exponents from 1e16, and plain notation down to 1e-4.

to_float(value)

(since 0.1.0)
@spec to_float(term()) :: {:ok, float()} | :error

Converts a value to a float, as Python's float() does.

Returns :error for nil, containers and non-numeric strings.

to_integer(value)

(since 0.1.0)
@spec to_integer(term()) :: {:ok, integer()} | :error

Converts a value to an integer, as Python's int() does: floats truncate toward zero, booleans are 0/1, strings must be integer literals.

to_string(value)

(since 0.1.0)
@spec to_string(term()) :: String.t()

Renders a value as interpolated text.

truthy?(value)

(since 0.1.0)
@spec truthy?(term()) :: boolean()

Python truthiness of a decoded JSON value.