Sign in Join
FPDoc Onlineexperiment

Trunc function

In unit System

Truncate a floating point value.

Declaration

pascal
function Trunc(d: ValReal): Int64

Description

Trunc returns the integer part of X, which is always smaller than (or equal to) X in absolute value.

Errors

An invalid floating point operation error may occur in one of several conditions:

  • Infinity or NegInfinity is specified.
  • Nan is specified.
  • X is out of the valid range of integers.

See also

Example: ex70

pascal
Program Example70;

{ Program to demonstrate the Trunc function. }

begin
  Writeln (Trunc(123.456));  { Prints 123  }
  Writeln (Trunc(-123.456)); { Prints -123 }
  Writeln (Trunc(12.3456));  { Prints 12   }
  Writeln (Trunc(-12.3456)); { Prints -12  }
end.

Example: ex124

pascal
program ex124;

{
  Example to show various error conditions for the Trunc() function.
  SysUtils is used to convert the runtime error to an exception that can be caught
  Math is used to have access to Nan and (Neg)Infinity
 
}

{$mode objfpc}
{$h+}
uses

  sysutils, math;
var
  D: Double;
  Q: QWord;
  L: Int64;
begin
  D := 2.0 * High(QWord);
  try
    Q := Trunc(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := NaN;
  try
    Q := Trunc(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := Infinity;
  try
    Q := Trunc(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := NegInfinity;
  try
    Q := Trunc(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := -2.0 * High(QWord);
  try
    L := Trunc(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
end.

An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.