Pascal: Convert Integer to String

program inttostr;

var   n: integer;
        numstring, numstring2, result : ANSIstring;
        x : char;

procedure string_reverse (var numstring : string);
var i, k : integer;
      temp : string;
begin
  k := 1;
  for i := length (numstring) downto 1 do
    begin
      temp[k] := numstring[i];
      inc (k);
    end;
  numstring := temp;
end;

function int_convert (n : integer) : string;
var divisor, remainder : integer;
begin
  divisor := 10;
  numstring := '';
  while not (n = 0) do
    begin
      remainder := n mod divisor;
      numchar := chr (remainder + ord('0'));
      numstring := numstring + numchar;
      n := n div 10;
    end;
  string_reverse (numstring);
  int_convert := numstring;
end;

begin
  writeln ('Enter an integer to convert to a string:');
  readln (n);
  result := int_convert (n);
  writeln ('String is ', result);
  str(n, numstring2);
  writeln ('Using str() the string is ', numstring2);
  readln (x);
end.

It is instructive to think how the procedure works, how individual digits are extracted from a number and converted to their string equivalent. For an integer we start on the right of the string (the units) and find the remainder after division by 10 - this becomes the right-most digit of the string. We then divide the number by 10 to remove the remainder part. Given 123 as input we have:

123 mod 10 = 3 - add this to the string: '3'
123 div 10 = 12

We then repeat the mod and div on the new number, until the number is 0:

12 mod 10 = 2 - add this to the string: '32'
12 div 10 = 1
1 mod 10 = 1 - add this to the string: '321'
1 div 10 = 0

We now reverse the string to give us '123'.

Object Pascal provides the procedure Str to convert a number to a string. Str has two parameters:

Str (number, numeric string). 

The number is the input number, eg 5 or 5.567. The numeric string parameter is the result. 

Back to questions