這是一個四舍五入的函數(shù),具體用法 myround(1.999,2) = 2.00 第一位1.999為要四舍五入的數(shù),2為要取的小數(shù)位。
歡迎大家測試探討。QQ:81392790
function myround(const yuan: Extended; const pp: Integer): Extended;
//yuan:原浮點數(shù),PP保留 小數(shù)點后第幾位
var
 p,l,m,l2:Longint;
 s:string; // 原浮點數(shù)
 sq:string; // 小數(shù)點前
 sh:string;//小數(shù)點后
begin
 if yuan=0 then exit;// 原浮點數(shù) 0
 if pp<0 then exit; //非法小數(shù)點后第幾位
 s:=floattostr(yuan);
 p:=pos('.',s);   //小數(shù)點位置
 sq:=midstr(s,1,p-1);
 sh:=midstr(s,p+1,length(s)-length(sq)-1);
 l:=length(sh);//小數(shù)位數(shù)
 l2:=length(sq);//整數(shù)位數(shù)
 if pp>=l then
  begin//0
   result:=strtofloat(s);
   exit;//比如 11。06 要保留到 小數(shù)點后第3位顯然 不合理
  end;//
{ if pp=l then  //比如 11。06 要保留到 小數(shù)點后第2位不用處理 直接返回
   begin//1
     Result:=s;
     exit;
   end;//1 }
  if pp<l then //比如 11。06 要保留到 小數(shù)點后第1位 ,。。。
  begin//2
    m:=strtoint(sh[pp+1]);
    if m>=5 then
    begin
      if pp>=1 then //保留到 小數(shù)點后第1,2。。。位
      begin//3
       sh:=midstr(sh,1,pp);
       sh := inttostr(strtoint(sh)+1);
       if length(sh)>pp then
       begin
          sh:= midstr(sh,2,pp);
          sq:= inttostr(strtoint(sq)+1);
       end;
      Result:=strtofloat(sq+'.'+sh);
      exit;
      end//3
      else  //保留到 小數(shù)點后第0位
      begin//4
       sq[l2]:=chr(ord(sq[l2])+1);
       Result:=strtofloat(sq);
       exit;
      end;//4
    end
    else
    begin
      if pp>=1 then //保留到 小數(shù)點后第1,2。。。位
      begin//3
       sh:=midstr(sh,1,pp);
       Result:=strtofloat(sq+'.'+sh);
      exit;
      end//3
      else  //保留到 小數(shù)點后第0位
      begin//4
       Result:=strtofloat(sq);
       exit;
      end;//4
    end;
  end;//2
end;
新聞熱點
疑難解答