gpt4 book ai didi

function - Delphi 将字节格式化为 GB

转载 作者:行者123 更新时间:2023-12-03 15:23:23 25 4
gpt4 key购买 nike

我正在使用以下函数将字节格式化为更易于理解的格式,但它返回了错误的信息。

 //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 (作者:扎尔科·加吉克)

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

最佳答案

问题是算术溢出。您可以像这样重写该函数:

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;

关于function - Delphi 将字节格式化为 GB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com