将一个浮点数转换为不小于或不大于该值的最小或最大整数

function RoundX(v: Double): Double;
var
  APower: Integer;
  ANeg: Boolean;
begin
  if IsZero(v) then
    Result := 0
  else
  begin
    APower := 0;
    ANeg := v < 0;
    if ANeg then
      v := -v;
    while v < 1 do
    begin
      v := v * 10;
      Dec(APower);
    end;
    while v > 10 do
    begin
      v := v / 10;
      Inc(APower);
    end;
    if not IsZero(v - Trunc(v)) then
      Result := (Trunc(v) + 1) * power(10, APower)
    else
      Result := Trunc(v) * power(10, APower);
    if ANeg then
      Result := -Result;
  end;
end;

RoundX(1.5) =  2

RoundX(123) = 200

RoundX(-1.5) = -2

RoundX(-123)=-200

分享到: