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.
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
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, "."}
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