Type conversions

A term does not become another type by being used in a different place: an integer is not a string, a string is not a binary, and an atom is not text. The conversion is an ordinary function with a name and a return value, and it is the caller who decides what the program needs. This lesson collects the conversions between the types Erlang uses most.

Numbers and text

integer_to_list/1 and integer_to_binary/1 write a number as text; list_to_integer/1 and binary_to_integer/1 read it back and accept a base as the second argument. trunc/1, round/1 and float/1 convert between the two number types, and they round in different directions:

erl

1> trunc(-3.7). -3 2> round(-3.7). -4 3> round(2.5). 3 4> float(7). 7.0 5> integer_to_list(42). "42" 6> list_to_integer("42"). 42 7> integer_to_binary(255, 16). <<"FF">> 8> binary_to_integer(<<"ff">>, 16). 255

trunc/1 cuts toward zero, so -3.7 becomes -3; round/1 goes to the nearest integer and a half away from zero, so -3.7 becomes -4 and 2.5 becomes 3. The base argument works for any base from 2 to 36, and the digits above 9 are printed in upper case.

The text these functions accept is strict: no spaces, no decimal point, no prefix. list_to_integer("3.5") fails with bad argument and names the argument that was not an integer, while list_to_float("3.5") reads the float. Nothing is converted silently, which is the point: a value that comes from a file is read with a function the caller chose, not by an implicit cast.

Atoms and text

atom_to_list/1 and atom_to_binary/2 write an atom as text, and list_to_atom/1, binary_to_atom/2 and binary_to_existing_atom/2 read it back. The second argument of the binary forms is the encoding, almost always utf8. The existing form refuses to make a new atom, which is the one to use on text from outside:

erl

1> atom_to_binary(ok, utf8). <<"ok">> 2> binary_to_atom(<<"ready">>, utf8). ready 3> binary_to_existing_atom(<<"ok">>, utf8). ok 4> atom_to_list(ok). "ok"

binary_to_existing_atom(<<"never_seen">>, utf8) raises badarg because the atom was never made, so a parser over input cannot fill the atom table. The atoms lesson explains the table and its limit.

Lists and binaries

list_to_binary/1 turns a list of bytes into a binary, and binary_to_list/1 turns a binary back into a list of bytes. unicode:characters_to_binary/1 encodes a list of characters, including characters above 255, as UTF-8:

erl

1> list_to_binary("hi"). <<"hi">> 2> binary_to_list(<<"hi">>). "hi" 3> unicode:characters_to_binary("héllo"). <<"héllo"/utf8>> 4> iolist_to_binary(["a", [98], <<"c">>]). <<"abc">>

The last line is the conversion to reach for when a string is built from pieces: an iolist is a list that holds bytes, strings, binaries and nested iolists, and iolist_to_binary/1 flattens it in one pass without making an intermediate string for every piece.

The iolist

A message is usually a mix of fixed text and values, and the natural way to build it is a list of parts. io_lib:format/2 returns exactly such a list, and iolist_to_binary/1 makes the binary a socket can send. This program builds a greeting from a name, a count and a number converted by hand:

iolist.erl

-module(iolist). -export([main/0]). main() -> Name = "Ada", Count = 3, Parts = ["Hello, ", Name, "! You have ", integer_to_list(Count), " messages."], io:format("~s~n", [iolist_to_binary(Parts)]).

erlc iolist.erl

erl -noshell -eval 'iolist:main(), halt().'

Hello, Ada! You have 3 messages.

Parts is not flattened until the last line, so each piece keeps its type: the strings stay lists, the number becomes a string with integer_to_list/1, and the binary is made once. The io:format and output lesson shows the format directives that replace the hand-built pieces.

A conversion that composes

The conversions chain naturally, because each one returns an ordinary value. This module converts both ways in one expression and prints each step:

convert.erl

-module(convert). -export([main/0]). main() -> io:format("~p~n", [trunc(3.9)]), io:format("~p~n", [round(3.5)]), io:format("~p~n", [float(7)]), io:format("~p~n", [integer_to_list(42)]), io:format("~p~n", [list_to_integer("42")]), io:format("~p~n", [integer_to_binary(255, 16)]), io:format("~p~n", [binary_to_integer(<<"ff">>, 16)]).

erlc convert.erl

erl -noshell -eval 'convert:main(), halt().'

3 4 7.0 "42" 42 <<"FF">> 255

~p prints the result of each step with its type visible: a string in quotes, a float with its point, a binary with its brackets. The JSON lesson uses the same conversions to write and read a document, and term_to_binary/1 turns a whole term into a binary in one call.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does trunc(-3.7) return?

    Answer

    -3

    trunc/1 cuts toward zero, so the fraction is dropped and the sign stays.

  2. What does round(-3.7) return?

    Answer

    -4

    round/1 goes to the nearest integer, and -3.7 is nearer to -4.

  3. What does float(7) return?

    Answer

    7.0

    float/1 converts an integer to the float with the same value.

  4. What does integer_to_binary(255, 16) return?

    Answer

    <<"FF">>

    The base is 16 and the digits above 9 are printed in upper case, so the binary is <<"FF">>.

  5. What does list_to_integer("3.5") do?

    Answer

    Raises badarg, and list_to_float/1 reads the float

    list_to_integer/1 accepts only the textual form of an integer, so the decimal point makes the argument invalid.

  6. Which function turns a list of characters into a binary?

    Answer

    list_to_binary/1

    list_to_binary/1 takes the bytes of the list; iolist_to_binary/1 also flattens nested lists and binaries.

  7. Which function converts a binary to an atom that must already exist?

    Answer

    binary_to_existing_atom/2

    binary_to_existing_atom/2 raises badarg instead of adding a new atom to the table.

  8. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [trunc(3.9)]).

    Answer

    3

    trunc/1 drops the fraction, so 3.9 becomes the integer 3.

  9. What does this module print? -module(q2). -export([main/0]). main() -> Parts = ["Hello, ", "Ada", "!"], io:format("~s~n", [iolist_to_binary(Parts)]).

    Answer

    Hello, Ada!

    iolist_to_binary/1 joins the parts without adding anything between them.

  10. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [binary_to_integer(<<"101">>, 2)]).

    Answer

    5

    The base 2 makes 101 the binary number five.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev