# `Money.Input.Cast`
[🔗](https://github.com/ex-money/money_input/blob/v0.3.3/lib/money/input/cast.ex#L1)

Casts a form-submission shape into a `t:Money.t/0`.

`cast/2` consumes the four shapes a user-input pipeline can
produce:

* `nil` and blank-amount maps return `{:ok, nil}` — the field
  wasn't filled in.

* `t:Money.t/0` round-trips unchanged.

* `%{"amount", "currency"}` (or `%{amount, currency}`) — the
  nested form-submission shape that `<.money_input>` produces
  and that `Money.Ecto.Composite.Type` accepts. The amount
  field is built with `Money.new/3`; pass `:locale` if you
  need to parse a locale-formatted amount string.

* A bare binary (`"$1,234.56"`, `"1.234,56"`) delegates to
  `Money.parse/2`. Money.parse already handles surrounding
  whitespace, accounting parens, currency symbols and ISO
  codes.

The function is modelled after `Money.Ecto.Composite.Type.cast/2`
(in `money_sql`) so behaviour stays consistent across the two
paths. We host our own copy to avoid taking on `ecto_sql` as a
hard dependency.

# `input`

```elixir
@type input() ::
  nil | Money.t() | String.t() | %{required(String.t() | atom()) =&gt; term()}
```

Inputs accepted by `cast/2`. See the module docs.

# `cast`

```elixir
@spec cast(input(), Keyword.t()) :: {:ok, Money.t() | nil} | {:error, term()}
```

Casts a form-submission value to a `t:Money.t/0`.

### Arguments

* `input` is the value to cast (see `t:input/0`).

* `options` is a keyword list of options forwarded to
  `Money.new/3` for map inputs and `Money.parse/2` for string
  inputs.

### Options

* `:locale` — locale to use when parsing a locale-formatted
  amount string. Defaults to `Localize.get_locale/0`.

* `:currency` — fallback currency atom used only when the
  submitted map omits the `currency` key. Has no effect when
  the map provides one.

### Returns

* `{:ok, Money.t()}` on success.

* `{:ok, nil}` for blank input — `nil`, `""`, a map with an
  empty `amount`, or a map with no `amount` key at all.

* `{:error, term()}` if the cast fails — typically an
  `{exception, message}` tuple.

### Examples

    iex> Money.Input.Cast.cast(%{"amount" => "1234.56", "currency" => "USD"})
    {:ok, Money.new(:USD, "1234.56")}

    iex> Money.Input.Cast.cast(%{"amount" => "1.234,56", "currency" => "EUR"}, locale: :de)
    {:ok, Money.new(:EUR, "1234.56")}

    iex> Money.Input.Cast.cast(%{"amount" => "10"}, currency: :JPY)
    {:ok, Money.new(:JPY, "10")}

    iex> Money.Input.Cast.cast(%{"amount" => "", "currency" => "USD"})
    {:ok, nil}

    iex> Money.Input.Cast.cast(nil)
    {:ok, nil}

    iex> Money.Input.Cast.cast(Money.new(:GBP, "5.00"))
    {:ok, Money.new(:GBP, "5.00")}

---

*Consult [api-reference.md](api-reference.md) for complete listing*
