Number Parsing in Pascal

Our program demonstrates parsing numbers from strings, which is a common task in many applications. Here’s how to do it in Pascal:

program NumberParsing;

uses
  SysUtils;

var
  f: Double;
  i, d: Int64;
  u: QWord;
  k: Integer;
  e: Integer;

begin
  // With StrToFloat, we parse a floating-point number
  f := StrToFloat('1.234');
  WriteLn(f);

  // For StrToInt64, we parse a 64-bit integer
  i := StrToInt64('123');
  WriteLn(i);

  // StrToInt64 will recognize hex-formatted numbers with a '0x' prefix
  d := StrToInt64('$1c8');  // In Pascal, '$' is used for hex numbers instead of '0x'
  WriteLn(d);

  // For unsigned 64-bit integers, we use StrToQWord
  u := StrToQWord('789');
  WriteLn(u);

  // StrToInt is a convenience function for basic integer parsing
  k := StrToInt('135');
  WriteLn(k);

  // Parse functions raise an exception on bad input
  try
    k := StrToInt('wat');
  except
    on E: EConvertError do
      WriteLn(E.Message);
  end;
end.

In this Pascal program:

  1. We use the SysUtils unit, which provides number parsing functions.

  2. StrToFloat is used to parse floating-point numbers.

  3. StrToInt64 is used for parsing 64-bit integers. It can also handle hexadecimal numbers when prefixed with ‘$’.

  4. StrToQWord is used for parsing unsigned 64-bit integers.

  5. StrToInt is a convenience function for parsing basic integers.

  6. These functions raise an EConvertError exception when given invalid input, which we catch and handle in a try-except block.

To run the program, save it as number_parsing.pas and compile it with a Pascal compiler like Free Pascal:

$ fpc number_parsing.pas
$ ./number_parsing
1.2340000000000000E+000
123
456
789
135
Invalid integer value

Note that the exact output format of floating-point numbers may vary depending on your system and compiler settings.

Next, we’ll look at another common parsing task: URLs.