Onchange on number type input field

Hi there!
I have an input field with number type in a form. Behind this field is a schema field with float type.
When the value of this field change, it will run the phx-change of the form.

<.input field={{line, :quantity}} type="number" label="Quantity" step="0.01" />

When i enter only a number (e.g. 1), it throws an error:

[error] GenServer #PID<0.635.0> terminating
** (ArgumentError) errors were found at the given arguments:

  * 1st argument: not a textual representation of a float

    :erlang.binary_to_float("1")

I don’t think the phx-debounce is the solution to this.
How do you avoid this error? Thank you :slight_smile:

What’s the reason for using :erlang.binary_to_float/1 instead of Float.parse/1?

iex> :erlang.binary_to_float("1")
** (ArgumentError) errors were found at the given arguments:

  * 1st argument: not a textual representation of a float

    :erlang.binary_to_float("1")
    iex:2: (file)
iex> {num, _} = Float.parse("1")
{1.0, ""}
iex> num
1.0
iex> {num, _} = Float.parse("1.")
{1.0, "."}
1 Like

You can match the result in a with or case block and only modify the socket on success.

def handle_event("change", %{"quantity" => quantity}, socket) do
  socket =
    case Float.parse(quantity) do
      {float, _remainder_of_binary} -> assign(socket, :quantity, float)
      :error -> socket
    end

  {:noreply, socket}
end

Hey! Sorry for replying so late. Thank you, this worked well. I don’t know why, but for some reason i used String.to_float/1. :slight_smile:

No worries, I’ve made the same mistake before. I was just going off the error message but see now that String.to_float/1 inlines the :erlang function.