I have a stringified value that may be an integer or boolean ("20", "true"). I would like to cast the value to it's type, however, when I do a conversion on the wrong type, I get a runtime error:
iex> String.to_existing_atom("20")
** (ArgumentError) argument error
:erlang.binary_to_existing_atom("20", :utf8)
iex> String.to_integer("true")
** (ArgumentError) argument error
:erlang.binary_to_integer("true")
If you need to convert only integers and booleans from strings you may do something like this:
defmodule Converter do
def convert!("true"), do: true
def convert!("false"), do: false
def convert!(num), do: String.to_integer(num)
end
Sample usage:
iex(4)> Enum.map(["20", "true", "-5", "false"], &Converter.convert!/1)
[20, true, -5, false]
If you are dealing with json you may want to consider using a parsing library such as Poison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With