typestar

Format and field widths in Delphi

A ferry timetable printed as a three-column table whose numbers line up.

program StringFormat;
uses SysUtils;

const
  Route = 'Tarbert';
var
  Sailings: Integer;
  Crossing: Double;
begin
  Sailings := 6;
  Crossing := 34.5;
  // %s takes a string, %d an integer, %.2f two decimal places.
  WriteLn(Format('%s: %d sailings, %.2f minutes',
    [Route, Sailings, Crossing]));
  // A number after % is a field width; a minus sign left-aligns it.
  WriteLn(Format('%-12s%5s%9s', ['route', 'runs', 'minutes']));
  WriteLn(Format('%-12s%5d%9.2f', [Route, Sailings, Crossing]));
  WriteLn(Format('%-12s%5d%9.2f', ['Rhubodach', 18, 5.0]));
end.

How it works

  1. %s takes a string, %d an integer and %.2f a number with two decimals.
  2. %-12s left-aligns inside a twelve-wide field; %5d and %9.2f align right.
  3. The header row and both sailing rows share those widths, so the columns match.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
538
Tokens
110
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 2 of 3 in Types & strings, step 5 of 27 in Language basics.

← Previous Next →