ZetCode

Formatting output in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

Plain WriteLn prints values in their shortest form, which is fine for debugging and useless for a report. Pascal offers field widths and precision directly in the write parameters, the Format function in SysUtils, and the FormatFloat family for reals. This article shows how to align numbers and strings, choose decimal places, format numbers with thousands separators, and print a table with straight columns.

Field widths

A colon after a value sets the minimum field width. The value is right-aligned inside that width and is never truncated; if it needs more characters, the field grows. A second colon sets the number of decimal places for a real. A string is right-aligned in the same way, so 'Pascal':10 puts the spaces before the text.

widths.pas
program widths;
{$mode objfpc}{$H+}

begin
  WriteLn('[', 42:5, ']');
  WriteLn('[', 42:-5, ']');
  WriteLn('[', 3.14159:0:2, ']');
  WriteLn('[', 3.14159:8:2, ']');
  WriteLn('[', 3.14159:12:4, ']');
  WriteLn('[', 'Pascal':10, ']');
  WriteLn('[', 'Pascal':-10, ']');
end.

The number 42 occupies two characters and is padded to five. A negative width does not left-align it: 42:-5 prints without padding, and 'Pascal':-10 behaves the same way, so use Format or PadRight when a value has to be flushed left. A width of 0 means "use the minimum needed", which is why 3.14159:0:2 prints exactly two decimals without extra spaces.

$ fpc -gl widths.pas
$ ./widths
[   42]
[42]
[3.14]
[    3.14]
[      3.1416]
[    Pascal]
[Pascal]

Real numbers

Without a width, a real is printed in scientific notation with enough digits to show the stored value. The 0:2 form is usually what a report needs, and Format gives the same control with a template. The letter e in a template selects scientific notation.

scientific.pas
program scientific;
{$mode objfpc}{$H+}

uses SysUtils;

begin
  WriteLn(1.5e-9);
  WriteLn(1.5e-9:0:12);
  WriteLn(Format('%e', [12345.678]));
  WriteLn(Format('%.2e', [12345.678]));
end.

The default form shows the binary value with many digits, which is rarely wanted in output. 0:12 fixes the number of decimals, and %.2e combines scientific notation with two decimals. The unrounded %e form is useful only when the exact stored value matters.

$ fpc -gl scientific.pas
$ ./scientific
 1.50000000000000000002E-0009
0.000000001500
1.2345678000000000E+004
1.2E+004

The Format function

Format takes a template and an array of values. Each % introduces a placeholder: %s for a string, %d for a decimal integer, %f for a fixed-point real, %e for scientific notation, and %x or %X for hexadecimal. A minus sign after the percent left-aligns, and a number sets the minimum width.

formatting.pas
program formatting;
{$mode objfpc}{$H+}

uses SysUtils;

begin
  WriteLn(Format('Name: %s, age: %d', ['Alice', 30]));
  WriteLn(Format('Pi = %.3f', [Pi]));
  WriteLn(Format('[%8.2f]', [3.14159]));
  WriteLn(Format('[%-10s]', ['Pascal']));
  WriteLn(Format('[%10s]', ['Pascal']));
  WriteLn(Format('%x %X', [255, 255]));
  WriteLn(Format('%8d', [42]));
end.

The template can mix placeholders and literal text, and the values are taken from the array in order. %8.2f is a field of eight characters with two decimals, %-10s is a left-aligned string field of ten, and %x prints hexadecimal in lower case while %X prints it in upper case. A placeholder that does not match a value raises EConvertError at run time.

$ fpc -gl formatting.pas
$ ./formatting
Name: Alice, age: 30
Pi = 3.142
[    3.14]
[Pascal    ]
[    Pascal]
FF FF
      42

FormatFloat and FloatToStrF

FormatFloat uses a pattern string. The characters 0 and # stand for a digit that is always printed or only printed when significant, a comma groups thousands, and e selects scientific notation. FloatToStrF selects one of the predefined formats instead: ffFixed, ffGeneral, and ffExponent.

floats.pas
program floats;
{$mode objfpc}{$H+}

uses SysUtils;

var
  x: Double;

begin
  x := 1234.5678;
  WriteLn(FormatFloat('0.00', x));
  WriteLn(FormatFloat('#,##0.00', x));
  WriteLn(FormatFloat('0.0e+00', x));
  WriteLn(FloatToStrF(x, ffFixed, 8, 2));
  WriteLn(FloatToStrF(x, ffGeneral, 6, 2));
  WriteLn(FloatToStrF(x, ffExponent, 6, 2));
end.

The first pattern always prints two decimals. The second adds a thousands separator, and the third uses scientific notation with one decimal. The FloatToStrF calls show the same value in fixed, general, and exponential form; the third argument controls the precision and the fourth the number of decimals where the format uses it. The decimal separator follows the current locale, so a machine with a comma locale prints 1234,57 instead of 1234.57.

$ fpc -gl floats.pas
$ ./floats
1234.57
1,234.57
1.2e+03
1234.57
1234.57
1.23457E+03

Padding strings

StrUtils provides PadLeft and PadRight for strings. Both take the string and the desired total length and pad with spaces. AddChar pads with a chosen character, which is how a number is given leading zeros without a format placeholder.

padding.pas
program padding;
{$mode objfpc}{$H+}

uses StrUtils;

begin
  WriteLn('[', PadLeft('7', 3), ']');
  WriteLn('[', PadLeft('Pascal', 10), ']');
  WriteLn('[', PadRight('Pascal', 10), ']');
  WriteLn('[', AddChar('*', 'x', 5), ']');
end.

PadLeft('7', 3) produces two spaces and the digit, while PadRight('Pascal', 10) puts the spaces after the text. AddChar('*', 'x', 5) repeats the fill character until the result is five characters long, so the text ends up on the right. A string that is already longer than the requested width is returned unchanged.

$ fpc -gl padding.pas
$ ./padding
[  7]
[    Pascal]
[Pascal    ]
[****x]

A table

A report is a table with a header, a separator line, and one row per record. The next program combines Format with a helper function and a const array. Every column has a fixed width, so the values line up even when the names have different lengths.

table.pas
program table;
{$mode objfpc}{$H+}

uses SysUtils, StrUtils;

function Grade(score: Integer): string;
begin
  if score >= 90 then
    Result := 'A'
  else if score >= 80 then
    Result := 'B'
  else
    Result := 'C';
end;

const
  Names: array[1..4] of string = ('Alice', 'Bob', 'Caroline', 'Dan');
  Scores: array[1..4] of Integer = (92, 78, 85, 60);

var
  i: Integer;

begin
  WriteLn(Format('%-10s %6s %8s', ['Name', 'Score', 'Grade']));
  WriteLn(StringOfChar('-', 26));
  for i := 1 to 4 do
    WriteLn(Format('%-10s %6d %8s', [Names[i], Scores[i], Grade(Scores[i])]));
end.

The header and the rows use the same widths, which is what keeps the columns straight. StringOfChar('-', 26) builds the separator line, and the grade is computed by an ordinary function rather than a nested conditional inside the template. The same layout works for any number of rows; only the loop bound changes.

$ fpc -gl table.pas
$ ./table
Name        Score    Grade
--------------------------
Alice          92        A
Bob            78        C
Caroline       85        B
Dan            60        C

Next steps

The reading input article reads the values that these templates print, and the string processing article supplies the split and replace routines behind a report. The numeric functions article explains the rounding that happens before a real is formatted.

Source

Free Pascal: Format

Free Pascal: FormatFloat

Pascal on Wikipedia

In this article we have set field widths and precision, printed reals in fixed and scientific notation, used Format, FormatFloat, and FloatToStrF, padded strings, and built an aligned table. The series continues with reading input in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.