Allow String.to_integer/1 to return integer when passed integer argument

45 views
Skip to first unread message

Curtis Rock

unread,
Jan 11, 2022, 9:05:27 PM1/11/22
to elixir-lang-core
I propose that String.to_integer/1 return an integer rather than raising an error when passed an integer argument.

Use case: When working with Phoenix LiveView and HEEx templates, database table id values are processed as both binary values and integer values, but must be converted back to integer when writing to the database.

When String.to_integer/1 is passed an integer value, it raises an error.

We add functions in our projects to make string to integer conversion more forgiving, such as the following functions found in the elixir library

defp to_integer(integer) when is_integer(integer), do: integer


defp to_integer(integer) when is_binary(integer), do: String.to_integer(integer)

José Valim

unread,
Jan 12, 2022, 1:41:09 AM1/12/22
to elixir-l...@googlegroups.com
Hi Curtis,

All functions in String accept a string only as first argument, so I would be wary of making an exception. We could perhaps allow it in Integer.parse/2 but I am not sure if we should make an exception there either, especially when we consider there are other arguments such as base and what they should mean when an integer is given.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/2fdcbff9-5551-4e91-aea1-68fc7447adfan%40googlegroups.com.

Wojtek Mach

unread,
Jan 12, 2022, 2:54:11 AM1/12/22
to elixir-lang-core
If your project is already using Ecto, you can also use Ecto.Type.cast/2:

iex(2)> Ecto.Type.cast(:integer, 42)
{:ok, 42}
iex(3)> Ecto.Type.cast(:integer, "42")
{:ok, 42}

(same for floats, dates, etc)

Probably best to wrap it in a more convenient function like this though:

defmodule MyApp do
  def cast!(type, term) do
    {:ok, casted} = Ecto.Type.cast(type, term)
    casted
  end
end
Reply all
Reply to author
Forward
0 new messages