3

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")

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

By definition String.to_existing_atom/1 will fail if there is no existing atom with such name. If you forcefully create atom for given string (be careful as atoms aren't GC-ed so you can DoS yourself by that) you need to use String.to_atom/1.

However if you want to parse binary and get value from it then you can use:

Comments

-1

Take a look at WannabeBool library. Not the solution for the example, but useful to convert strings to boolean.

WannabeBool.to_boolean("true")
true

WannabeBool.to_boolean("false")
false

1 Comment

adding a dependency for 20 lines of code that this library provides is not worth it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.