Number Parsing in Erlang

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

-module(number_parsing).
-export([main/0]).

main() ->
    % With string:to_float/1, we can parse floating-point numbers
    {F, _} = string:to_float("1.234"),
    io:format("~p~n", [F]),

    % For parsing integers, we use string:to_integer/1
    {I, _} = string:to_integer("123"),
    io:format("~p~n", [I]),

    % string:to_integer/1 will recognize hex-formatted numbers when
    % prefixed with "0x"
    {D, _} = string:to_integer("0x1c8"),
    io:format("~p~n", [D]),

    % For parsing unsigned integers, we can use the same function
    {U, _} = string:to_integer("789"),
    io:format("~p~n", [U]),

    % list_to_integer/1 is a convenience function for basic base-10
    % integer parsing
    K = list_to_integer("135"),
    io:format("~p~n", [K]),

    % Parse functions return an error for bad input
    case string:to_integer("wat") of
        {error, Reason} -> io:format("Error: ~p~n", [Reason]);
        _ -> ok
    end.

In Erlang, we use the string module for parsing numbers from strings. The string:to_float/1 function is used for parsing floating-point numbers, while string:to_integer/1 is used for parsing integers.

For string:to_float/1, the function returns a tuple where the first element is the parsed float and the second is the rest of the string (which we ignore with _).

Similarly, string:to_integer/1 returns a tuple with the parsed integer and the rest of the string. It can also recognize hex-formatted numbers when they’re prefixed with “0x”.

Erlang doesn’t have a separate function for parsing unsigned integers, so we use the same string:to_integer/1 function.

The list_to_integer/1 function is a convenience function for basic base-10 integer parsing.

For error handling, the parse functions will return {error, Reason} for bad input. We demonstrate this with a case statement at the end of the example.

To run the program:

$ erlc number_parsing.erl
$ erl -noshell -s number_parsing main -s init stop
1.234
123
456
789
135
Error: no_integer

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