User Tools

Site Tools


cs326:formatted_output

This is an old revision of the document!


Formatted Output using :io.format

The Erlang library :io includes a format function that works in a way analogous to System.out.printf, but of course the details are different…very different. One thing in particular, that I tend to forget: the format function takes two arguments: the format string and a list of zero or more variables and literals to be output.

We'll explore it in a series of examples:

iex> :io.format("hello world~n", [])
hello world
:ok

iex> :io.format("this outputs one Elixir number: ~b~n", [-999])
this outputs one Elixir term: -999
:ok

iex> :io.format("this outputs a floating-point number: ~f~n", [5.678])
The number is 5.678
:ok

iex> :io.format("this outputs the same but with just one digit to the right of the decimal: ~3.1f~n", [5.678])
The number is 5.7
:ok

iex> :io.format("this outputs a floating-point number on a line by itself:~n ~3.1f~n", [5.678])
The number is 
5.7
:ok

iex> :io.format("this outputs one Elixir term: ~w~n", [:hello])
this outputs one Elixir term: hello
:ok

iex> :io.format("this outputs one Elixir term: ~w~n", ["hello"])
this outputs one Elixir term: <<104,101,108,108,111>>
:ok

iex> :io.format("this outputs two Elixir terms: ~w ~w~n", [:hello, :world])
this outputs two Elixir terms: hello world
:ok

iex> :io.format("~-15w: ~b degrees C~n", [:moscow, -10]) # ~-15w sets a 15-character field, left justified
moscow         : -10 degrees C
:ok

iex> :io.format("list: ~p, tuple: ~p~n", [[1,2,3], {1,2}])
list: [1,2,3], tuple: {1,2}
:ok

Complete docs on the :io.format function are on the Erlang library website, but be warned, it is extensive. Note that in Erlang the function is invoked as io::format(…)

cs326/formatted_output.1518813961.txt.gz · Last modified: 2018/02/16 14:46 by scarl