加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

function – Delphi将字节格式化为GB

发布时间:2020-12-15 09:21:04 所属栏目:大数据 来源:网络整理
导读:我使用以下函数将字节格式化为更易于阅读的格式,但它返回的信息不正确. //Format file byte size function FormatByteSize(const bytes: LongInt): string; const B = 1; //byte KB = 1024 * B; //kilobyte MB = 1024 * KB; //megabyte GB = 1024 * MB; //gi
我使用以下函数将字节格式化为更易于阅读的格式,但它返回的信息不正确.

//Format file byte size
 function FormatByteSize(const bytes: LongInt): string;
 const
   B = 1; //byte
   KB = 1024 * B; //kilobyte
   MB = 1024 * KB; //megabyte
   GB = 1024 * MB; //gigabyte
 begin
   if bytes > GB then
     result := FormatFloat('#.## GB',bytes / GB)
   else
     if bytes > MB then
       result := FormatFloat('#.## MB',bytes / MB)
     else
       if bytes > KB then
         result := FormatFloat('#.## KB',bytes / KB)
       else
         result := FormatFloat('#.## bytes',bytes) ;
 end;

例:

procedure TForm1.Button1Click(Sender: TObject);
begin
 ShowMessage(FormatByteSize(323889675684)); //Returns 1.65GB when it should be ~301GB
end;

参考文献:http://delphi.about.com/od/delphitips2008/qt/format-bytes.htm(作者:Zarco Gajic)

任何人都可以解释为什么它返回不正确的信息,更重要的是知道如何修复它,以便它返回正确的信息?

解决方法

问题是算术溢出.你可以像这样重写这个函数:

uses
  Math;

function ConvertBytes(Bytes: Int64): string;
const
  Description: Array [0 .. 8] of string = ('Bytes','KB','MB','GB','TB','PB','EB','ZB','YB');
var
  i: Integer;
begin
  i := 0;

  while Bytes > Power(1024,i + 1) do
    Inc(i);

  Result := FormatFloat('###0.##',Bytes / Power(1024,i)) + #32 + Description[i];
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读