whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

33 Visitors Online


 
...round a number correctly?
Autor: Simon Grossenbacher
Homepage: http://www.swissdelphicenter.ch
[ Print tip ]  

Tip Rating (7):  
     


{
  The function Round of the Delphi doesn't work
  like it is usually expected.
  The odd numbera are rounded down and the even numbers up.

  Die Round Funktion in Delphi gibt normalerweise nicht
  die erwartete Zahl zurück.
  Die ungeraden Zahlen werden abgerundet, die geraden aufgerundet

  Example/ Beispiel:

  x:= Round(17.5) = x = 18

  x:= Round(12.5) = x = 12
}

function DoRound(const X: Extended): Int64;
begin
  
Result := 0;
  if X0 then
    
Result := trunc(X + 0.5);
  if Xthen
    Result := trunc(X - 0.5);
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  
ShowMessage(FormatFloat('0.00', DoRound(17.5)));  // - 18
  
ShowMessage(FormatFloat('0.00', DoRound(12.5)));  // - 13

  //This rounds every value to 0.05 steps
  //Rundet in 0.05 Schritten
  
ShowMessage(FormatFloat('0.00', Round(17.22 / 0.05) * 0.05)); // - 17.20
end;


{***Another function:***}

function RoundUp(Value: Extended): Int64;
  procedure Set8087CW(NewCW: Word);
  asm
         
MOV     Default8087CW,AX
         FNCLEX
         FLDCW   Default8087CW
 end;
const
  
RoundUpCW = $1B32;
var
  
OldCW: Word;
begin
  
OldCW := Default8087CW;
  try
    
Set8087CW(RoundUpCW);
    Result := Round(Value);
  finally
    
Set8087CW(OldCW);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  
ShowMessage(FormatFloat('0.00', RoundUp(19.32)));  // - 19
end;


 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners