当前位置:主页>Delphi教程>文章内容
一个四舍五入的函数
来源: 作者: 发布时间:2007-04-29  

这是一个四舍五入的函数,具体用法 myround(1.999,2) = 2.00 第一位1.999为要四舍五入的数,2为要取的小数位。

欢迎大家测试探讨。QQ:81392790

function myround(const yuan: Extended; const pp: Integer): Extended;
//yuan:原浮点数,PP保留 小数点后第几位
var
 p,l,m,l2:Longint;
 s:string; // 原浮点数
 sq:string; // 小数点前
 sh:string;//小数点后
begin
 if yuan=0 then exit;// 原浮点数 0
 if pp<0 then exit; //非法小数点后第几位
 s:=floattostr(yuan);
 p:=pos('.',s);   //小数点位置
 sq:=midstr(s,1,p-1);
 sh:=midstr(s,p+1,length(s)-length(sq)-1);
 l:=length(sh);//小数位数
 l2:=length(sq);//整数位数
 if pp>=l then
  begin//0
   result:=strtofloat(s);
   exit;//比如 11。06 要保留到 小数点后第3位显然 不合理
  end;//
{ if pp=l then  //比如 11。06 要保留到 小数点后第2位不用处理 直接返回
   begin//1
     Result:=s;
     exit;
   end;//1 }
  if pp<l then //比如 11。06 要保留到 小数点后第1位 ,。。。
  begin//2
    m:=strtoint(sh[pp+1]);
    if m>=5 then
    begin
      if pp>=1 then //保留到 小数点后第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  //保留到 小数点后第0位
      begin//4
       sq[l2]:=chr(ord(sq[l2])+1);
       Result:=strtofloat(sq);
       exit;
      end;//4
    end
    else
    begin
      if pp>=1 then //保留到 小数点后第1,2。。。位
      begin//3
       sh:=midstr(sh,1,pp);
       Result:=strtofloat(sq+'.'+sh);
      exit;
      end//3
      else  //保留到 小数点后第0位
      begin//4
       Result:=strtofloat(sq);
       exit;
      end;//4
    end;
  end;//2
end;


 
上一篇:我写的采用csv格式将数据转换为excel的函数,带有分栏功能   下一篇:事件的危机——调试手记之一
 
  相关文章
·我写的采用csv格式将数据转换为excel的
·事件的危机——调试手记之一
·用Delphi建立通讯与数据交换服务器—Tr
·窗体的建立时机及缓冲的思想在ini文件
·用Delphi编写Win2000服务程序
·通用查询组件设计(续三)
·如何用idFTP遍历整个目录----下载、删
·通用查询组件设计(续四)
·Delphi例程-应用程序级信息
·在Delphi7中实现停靠功能
·获取其他进程中ListBox和ComboBox的内
·Delphi例程-文件管理例程(1~15)
 
【关闭窗口】
推荐本站资源
最新文章