Localize.Inputs.Number.Parser (Localize.Inputs.Number v0.1.1)

Copy Markdown View Source

Front-door parser for locale-aware number form input.

Delegates to Localize.Number.Parser.parse/2. The input layer does no parsing of its own — this module is a thin policy layer that adds form-input tolerance (paste artefacts, accounting parentheses, NBSP normalisation) before forwarding.

Summary

Functions

Parses a locale-formatted number from a user-typed string.

Normalises a parsed value to its canonical period-decimal string form — what a JS-driven form submission expects.

Functions

parse_number(string, options \\ [])

@spec parse_number(String.t() | nil, Keyword.t()) ::
  {:ok, Decimal.t() | integer() | nil} | {:error, term()}

Parses a locale-formatted number from a user-typed string.

Arguments

  • string is the raw user input.

  • options is a keyword list of options.

Options

  • :locale — the locale to interpret the string under. Defaults to Localize.get_locale/0.

  • :integer — when true, only integers are accepted.

Returns

  • {:ok, Decimal.t()} (or {:ok, integer()} when integer: true).

  • {:ok, nil} for blank input.

  • {:error, Exception.t() | {module(), String.t()}} on parse failure.

Examples

iex> Localize.Inputs.Number.Parser.parse_number("1,234.56", locale: :en)
{:ok, Decimal.new("1234.56")}

iex> Localize.Inputs.Number.Parser.parse_number("1.234,56", locale: :de)
{:ok, Decimal.new("1234.56")}

iex> Localize.Inputs.Number.Parser.parse_number("", locale: :en)
{:ok, nil}

iex> Localize.Inputs.Number.Parser.parse_number("(1,234.56)", locale: :en)
{:ok, Decimal.new("-1234.56")}

to_canonical(value)

@spec to_canonical(Decimal.t() | integer() | nil) :: String.t() | nil

Normalises a parsed value to its canonical period-decimal string form — what a JS-driven form submission expects.

Arguments

  • value is a Decimal, integer, or nil.

Returns

  • A binary in canonical period-decimal form.

  • nil when the input is nil.

Examples

iex> Localize.Inputs.Number.Parser.to_canonical(Decimal.new("1234.56"))
"1234.56"

iex> Localize.Inputs.Number.Parser.to_canonical(nil)
nil