ZetCode

Floating-point arithmetic in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

Pascal has three floating-point types: Single, Double, and Extended. They differ in size and precision, and the choice between them matters when a computation accumulates many operations or compares values that came from different expressions. This article shows the storage sizes, explains why 0.1 + 0.2 is not exactly 0.3, covers NaN and infinity, demonstrates banker's rounding, improves a long sum with the Kahan algorithm, and formats the results for display.

The real types

Single occupies 4 bytes and carries about 7 decimal digits, Double occupies 8 bytes and carries about 15, and Extended occupies 10 bytes on x86-64 and carries about 19. A real literal without a type is a Single in ObjFPC, while the Real alias is a Double; typed constants keep the type that is written. The extra precision of Double over Single is visible immediately when one third is computed at each precision.

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

uses SysUtils;

const
  OneS: Single = 1.0;    ThreeS: Single = 3.0;
  OneD: Double = 1.0;    ThreeD: Double = 3.0;
  OneE: Extended = 1.0;  ThreeE: Extended = 3.0;

var
  S: Single;
  D: Double;
  E: Extended;

begin
  S := OneS / ThreeS;
  D := OneD / ThreeD;
  E := OneE / ThreeE;

  WriteLn('Single:   ', S);
  WriteLn('Double:   ', D);
  WriteLn('Extended: ', E);
  WriteLn('sizes: ', SizeOf(S), ' ', SizeOf(D), ' ', SizeOf(E));
end.

All three values are one third, computed at the precision of its type. Single is already wrong at the seventh digit, Double prints 17 significant digits, and Extended prints 20. SizeOf confirms 4, 8, and 10 bytes. None of the three types can represent 0.1 or one third exactly, because the fraction has no finite base-2 expansion; the types only differ in how close they get.

$ fpc -gl types.pas
$ ./types
Single:    3.333333433E-01
Double:    3.3333333333333331E-001
Extended:  3.33333333333333333342E-0001
sizes: 4 8 10

Comparing reals

Because most decimal fractions are not exact, two expressions that should produce the same value can differ by a few units in the last place. Comparing them with = asks for exact bit equality and often returns False. The usual fix is to compare the absolute difference with a tolerance, or to call SameValue from the Math unit, which uses a scaled epsilon. The example adds 0.1 and 0.2 in variables and compares the sum with 0.3.

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

uses Math, SysUtils;

var
  A, B, C, X: Double;

begin
  A := 0.1;
  B := 0.2;
  C := 0.3;
  X := A + B;

  WriteLn('X = ', FloatToStr(X));
  WriteLn('X = C: ', X = C);
  WriteLn('X - C: ', FloatToStr(X - C));
  WriteLn('SameValue: ', SameValue(X, C));
  WriteLn('CompareValue: ', CompareValue(X, C, 1E-12));
end.

FloatToStr prints the sum as 0.3, but the exact comparison is false: the stored value is 0.30000000000000004, and subtracting 0.3 leaves 5.55E-17. SameValue returns true because the difference is below its default tolerance, and CompareValue returns 0 when the values are within the supplied 1E-12. Never compare a computed real with = unless the values are known to be exact copies of each other.

$ fpc -gl compare.pas
$ ./compare
X = 0.3
X = C: FALSE
X - C: 5.55111512312578E-17
SameValue: TRUE
CompareValue: 0

NaN and infinity

IEEE 754 defines special values for the results of undefined operations: NaN ("not a number") for 0/0 and infinity for 1/0. Whether an operation produces these values or raises an exception depends on the floating-point exception mask. By default, Free Pascal raises EZeroDivide for a real division by zero and EInvalidOp for 0/0. Calling SetExceptionMask with the arithmetic flags clears the mask, and the operations then return NaN and infinity instead.

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

uses Math, SysUtils;

var
  Zero, One: Double;
  N, Inf: Double;

begin
  SetExceptionMask([exInvalidOp, exZeroDivide, exOverflow, exUnderflow,
    exPrecision]);
  Zero := 0.0;
  One := 1.0;

  N := Zero / Zero;
  Inf := One / Zero;
  WriteLn('N = ', N);
  WriteLn('Inf = ', Inf);
  WriteLn('IsNan(N): ', IsNan(N));
  WriteLn('IsInfinite(Inf): ', IsInfinite(Inf));
  WriteLn('IsInfinite(-Inf): ', IsInfinite(-Inf));
  WriteLn('N = N: ', N = N);
end.

IsNan and IsInfinite test the special values without raising. NaN is not equal to anything, including itself, so N = N is false; this is the standard way to detect it, although IsNan is clearer. In a program that leaves the default mask in place, the same division would stop with an exception, which the exceptions article explains how to catch.

$ fpc -gl naninf.pas
$ ./naninf
N =                      Nan
Inf =                     +Inf
IsNan(N): TRUE
IsInfinite(Inf): TRUE
IsInfinite(-Inf): TRUE
N = N: FALSE

Rounding

Round returns the nearest integer, but when the value is exactly halfway between two integers it uses banker's rounding: it rounds to the even neighbour. Trunc drops the fractional part toward zero, Int returns the integer part as a real, and Frac returns the fractional part. Ceil and Floor always go up and down, and SimpleRoundTo from Math rounds a value to a number of decimal places with a different tie rule.

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

uses Math, SysUtils;

begin
  WriteLn('Round(2.5)  = ', Round(2.5));
  WriteLn('Round(3.5)  = ', Round(3.5));
  WriteLn('Round(-2.5) = ', Round(-2.5));
  WriteLn('Round(2.6)  = ', Round(2.6));
  WriteLn('Trunc(-2.7) = ', Trunc(-2.7));
  WriteLn('Int(-2.7)   = ', FloatToStr(Int(-2.7)));
  WriteLn('Frac(-2.7)  = ', FloatToStr(Frac(-2.7)));
  WriteLn('Ceil(-2.7)  = ', Ceil(-2.7));
  WriteLn('Floor(-2.7) = ', Floor(-2.7));
  WriteLn('SimpleRoundTo(2.5, 0) = ', FloatToStr(SimpleRoundTo(2.5, 0)));
end.

2.5 rounds to 2 and 3.5 rounds to 4, because 2 and 4 are even; -2.5 rounds to -2. Trunc(-2.7) is -2 because truncation goes toward zero, while Floor(-2.7) is -3. SimpleRoundTo(2.5, 0) gives 3, which shows that the two rounding routines are not interchangeable. Financial code should choose the rule that the domain requires and apply it explicitly.

$ fpc -gl rounding.pas
$ ./rounding
Round(2.5)  = 2
Round(3.5)  = 4
Round(-2.5) = -2
Round(2.6)  = 3
Trunc(-2.7) = -2
Int(-2.7)   = -2
Frac(-2.7)  = -0.7
Ceil(-2.7)  = -2
Floor(-2.7) = -3
SimpleRoundTo(2.5, 0) = 3

Kahan summation

Adding a small value to a large accumulator loses low bits: when the accumulator is much larger than the addend, the sum is rounded and the contribution of the addend disappears. Over many iterations the error adds up. The Kahan algorithm keeps a compensation term for the bits that were lost and adds them back at the next step, which reduces the error from linear in the number of terms to nearly constant.

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

uses SysUtils;

var
  I: Integer;
  Naive, Sum, C, Y, X: Double;

begin
  Naive := 0;
  Sum := 0;
  C := 0;
  for I := 1 to 1000000 do
  begin
    X := 0.1;
    Naive := Naive + X;

    Y := X - C;
    X := Sum + Y;
    C := (X - Sum) - Y;
    Sum := X;
  end;

  WriteLn('naive: ', FloatToStrF(Naive, ffExponent, 16, 4));
  WriteLn('kahan: ', FloatToStrF(Sum, ffExponent, 16, 4));
  WriteLn('error: ', FloatToStrF(Naive - Sum, ffExponent, 16, 4));
  WriteLn('exact: ', 1000000 * 0.1);
end.

The naive sum is 100000.0000013329 instead of 100000, an error of about 1.3E-6. The compensated sum is exactly 100000 in this run. The exact line is computed as a constant expression at the compiler's highest precision and printed with the Extended format, which is why it shows so many digits. For a long simulation, the compensation costs four extra operations per term and is usually worth it.

$ fpc -gl kahan.pas
$ ./kahan
naive: 1.000000000013329E+0005
kahan: 1.000000000000000E+0005
error: 1.332882675342262E-0006
exact:  1.00000000000000000000E+0005

Formatting the result

The default WriteLn format for a Double uses scientific notation with many digits, which is precise but hard to read. FloatToStr chooses a shorter representation, FloatToStrF takes an explicit format, precision, and digit count, and Format uses a format string. The formatted output article covers the field widths; this section compares the numeric formats.

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

uses SysUtils;

var
  X: Double;

begin
  X := 1234.5678;
  WriteLn('default:  ', X);
  WriteLn('FloatToStr: ', FloatToStr(X));
  WriteLn('ffFixed:  ', FloatToStrF(X, ffFixed, 8, 2));
  WriteLn('Format:   ', Format('%.3e', [X]));
  WriteLn('FormatFloat: ', FormatFloat('#,##0.00', X));
  WriteLn('scientific: ', FloatToStrF(X, ffExponent, 8, 3));
end.

ffFixed with two digits rounds to 1234.57, and FormatFloat('#,##0.00', X) adds the thousands separator, which is a comma in this locale. Format('%.3e', [X]) produces three digits after the decimal point in scientific notation. The FloatToStrF precision argument is the total number of significant digits for the exponent formats and the number of digits before the decimal point for ffFixed, so the two calls behave differently.

$ fpc -gl formatting.pas
$ ./formatting
default:   1.2345678000000000E+003
FloatToStr: 1234.5678
ffFixed:  1234.57
Format:   1.23E+003
FormatFloat: 1,234.57
scientific: 1.2345678E+003

Next steps

The numeric functions article collects the roots, powers, and trigonometric routines that operate on these types. The numerical integration article uses Extended accumulators and tolerances, and the linear algebra article compares pivots with a tolerance for the same reason. The bit manipulation article shows the integer representation that the sign, exponent, and mantissa are built from.

Source

Free Pascal Reference guide: real types

Free Pascal: SameValue

Kahan summation on Wikipedia

In this article we compared the three real types, saw why exact equality fails for decimal fractions, produced and tested NaN and infinity, applied banker's rounding and the other rounding routines, reduced summation error with Kahan's algorithm, and formatted the results. The series continues with big integers 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.