Mega Code Archive

 
Categories / Delphi / Examples
 

Rounding

The Round() function... As I recall it's a bug in the FPU of the processor itself, not Delphi, the FPU rounds to the nearest even number in the case of round (<number>.5) If X is exactly halfway between two whole numbers, the result is always the even number. I usually use something like this : (can be easily changed to a function, BTW) procedure RoundIt(var Amount : Double; Digits : Integer); var OneHalf, Power10 : Extended; begin If Digits > 19 then Digits := 19; If Digits < 0 then Digits := 0; Power10 := Power (10, Digits); If Amount < 0 then OneHalf:=-0.5 else OneHalf:=0.5; Amount := (Trunc(Amount * Power10 + OneHalf)) / Power10; end; Amount is the number you want to round, Digits is the number of decimals you want to keep. HTH (hope it's correct as well, cause I use it in several programs... Bert De Ridder Analyst/DBA Nissan Belgium [note: look also at the Trunc(), Ceil(), and Floor() functions...] *************************************************************** The way Delphi Round() function works depends on the value of the 8087 control word. This is set using the Set8087cw() procedure. The procedure take one parameter CW: Word, the default is in the global variable Default8087cw. The bitmasking etc.. for the is word is documented in Intel architecture manuals. To force the Round function to round up you can call the following during application startup. Set8087cw($1B32); You may want to wrap this into your own rounding function to preserve existing rounding behaviour. function RoundUp(Value: Extended): Int64; const RoundUpCW = $1B32; var OldCW: Word; begin OldCW := Default8087CW; try Set8087(RoundUpCW); result := Round(Value); finally Set8087CW(OldCW); end; end; end; This information and code is from Delphi in a Nutshell by Ray Lischner. I have mentioned before how valuable this book is. Regards, Anthony Richardson Sage Automation anthony_r@sageautomation.com