User Tools

Site Tools


cs326:formatted_output

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("Outputs one Elixir number: ~b~n", [-999])
Outputs one Elixir number: -999
:ok

iex> :io.format("Outputs a floating-point number: ~f~n", [5.678])
Outputs a floating-point number: 5.678000
:ok

iex> :io.format("Outputs the same but with just 3 digits to the right of the decimal: ~.3f~n", [5.678])
Outputs the same but with just 3 digits to the right of the decimal: 5.678
:ok

iex> :io.format("Outputs the same but with field width 3 and just 1 digit right of the decimal: ~3.1f~n", [5.678])
Outputs the same but with field width 3 and just 1 digit right of the decimal: 5.7
:ok

iex> :io.format("Outputs a floating-point number on a line by itself:~n ~3.1f~n", [5.678])
Outputs a floating-point number on a line by itself:
 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 two Elixir terms: ~w ~w~n", [:hello, :world])
this outputs two Elixir terms: hello world
:ok

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

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

iex> :io.format("~~w outputs any Elixir term: ~w~n", [-999])   
~w outputs any Elixir term: -999
:ok

iex> :io.format("~~w outputs any Elixir term: ~w~n", [[1, 2, 3]])
~w outputs any Elixir term: [1,2,3]
:ok
iex> 

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

iex> :io.format("~~p is like ~~w, but tries to be sensible with long lines ~p",        
...(10)> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]])
~p is like ~w, but tries to be sensible with long lines [1,2,3,4,5,6,7,8,9,10,
                                                         11,12,13,14,15,16,17,
                                                         18,19,20,21,22]:ok

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

cs326/formatted_output.txt · Last modified: 2018/02/16 15:00 by scarl