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.
To run the program, save it as number_parsing.exs
and use elixir
:
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.