Mega Code Archive

 
Categories / Delphi / Examples
 

Round a number correctly

Title: round a number correctly? { 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;