Number Parsing in Elixir

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Elixir.

# The built-in Float and Integer modules provide number parsing.

# With Float.parse, it returns a tuple with the parsed float and 
# the rest of the string, or :error if it fails.
{f, _} = Float.parse("1.234")
IO.puts(f)

# For Integer.parse, it returns a tuple with the parsed integer and
# the rest of the string, or :error if it fails.
{i, _} = Integer.parse("123")
IO.puts(i)

# Integer.parse will recognize hex-formatted numbers when given 
# the proper base.
{d, _} = Integer.parse("0x1c8", 16)
IO.puts(d)

# There's no direct equivalent to ParseUint, but you can use 
# Integer.parse and check if the result is positive.
{u, _} = Integer.parse("789")
IO.puts(u)

# String.to_integer is a convenience function for basic base-10
# integer parsing.
k = String.to_integer("135")
IO.puts(k)

# Parse functions return :error on bad input.
case Integer.parse("wat") do
  :error -> IO.puts("Error parsing integer")
  {num, _} -> IO.puts(num)
end

To run the program, save it as number_parsing.exs and use elixir:

$ elixir number_parsing.exs
1.234
123
456
789
135
Error parsing integer

In Elixir, number parsing is handled primarily by the Float and Integer modules. The Float.parse/1 and Integer.parse/1 functions return tuples containing the parsed number and any remaining string, or :error if parsing fails.

For parsing hexadecimal numbers, you can use Integer.parse/2 with a base of 16. Elixir doesn’t have a direct equivalent to ParseUint, but you can use Integer.parse/1 and check if the result is positive.

The String.to_integer/1 function provides a convenient way to parse base-10 integers, similar to Atoi in other languages.

Error handling in Elixir is often done using pattern matching, as shown in the last example where we use a case statement to handle the possibility of an error when parsing.

Next, we’ll look at another common parsing task: URLs.