Delphi tips :

Incorrect rounding with Delphi?


Delphi's Round function behaves in an unexpected way:

  • Odd nummers that end in .5 are rounded upwards, that's the traditional behavior, but...
  • Even numbers that end in .5 are rounded downwards!

This means:
i:= Round(11.5) // returns 12 ...but...
i := Round(10.5) // ...returns 10 !

Already since the first release of Borland Pascal, the Round function used a "bankers rounding" algorithm. While this is good for financial stuff, for other calculations we want traditional rounding, i.e. always round 0.5 upwards. This custom function gives the desired result:

function RoundCorrect(R: Real): LongInt;
  Result:= Trunc(R);       // extract the integer part 
  if Frac(R) >= 0.5 then   // if fractional part >= 0.5 then...
    Result := Result + 1;   // ...add 1

TOP   DelphiLand Club Membership  DC Library  Forum  Forum Archives  Crash Course Delphi  Tips  Source Code  Downloads  Links 

© Copyright 1999-2018 
Studiebureau Festraets