Sign in Join
FPDoc Onlineexperiment

Round function

In unit System

Round floating point value to nearest integer number.

Declaration

pascal
function Round(d: ValReal): Int64

Description

Round rounds X to the closest integer, which may be bigger or smaller than X.

In the case of .5, the algorithm uses "banker's rounding": .5 values are always rounded towards the even number.

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: ex54

pascal
Program Example54;

{ Program to demonstrate the Round function. }

begin
  Writeln (Round(1234.56));  { Prints 1235     }
  Writeln (Round(-1234.56)); { Prints -1235    }
  Writeln (Round(12.3456));  { Prints 12       }
  Writeln (Round(-12.3456)); { Prints -12      }
  Writeln (Round(2.5));      { Prints 2 (down) }
  Writeln (Round(3.5));      { Prints 4 (up)   }
    
end.

Example: ex125

pascal
program ex124;

{
  Example to show various error conditions for the Round() 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 := Round(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := NaN;
  try
    Q := Round(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := Infinity;
  try
    Q := Round(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := NegInfinity;
  try
    Q := Round(D);
  except
    on E: Exception do writeln(E.ClassName,': ',E.Message);  //EInvalidOp: Invalid floating point operation
  end;
  D := -2.0 * High(QWord);
  try
    L := Round(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.