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.
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:
Next, we’ll look at another common parsing task: URLs.