这是一个简单的(我认为)。
是否有系统内置函数,或者某人创建的可以从 Delphi 调用的函数,它将显示多个字节(例如文件大小),就像 Windows 在文件的属性框中显示的方式一样?
例如这是 Windows 属性框显示各种大小的方式:
539 bytes (539 bytes)
35.1 KB (35,974 bytes)
317 MB (332,531,365 bytes)
2.07 GB (2,224,617,077 bytes)
显示器可以巧妙地使用字节、KB、MB 或 GB,并且只显示 KB、MB 和 GB 的 3 个有效数字。然后,通过在括号中显示确切的字节数,用逗号分隔千位。这是一个非常好的展示,经过深思熟虑。
有人知道这样的功能吗?
编辑:我很惊讶没有这个功能。
感谢您提供有用的想法。我想出了这个,这似乎可行:
function BytesToDisplay(A:int64): string;
var
A1, A2, A3: double;
begin
A1 := A / 1024;
A2 := A1 / 1024;
A3 := A2 / 1024;
if A1 < 1 then Result := floattostrf(A, ffNumber, 15, 0) + ' bytes'
else if A1 < 10 then Result := floattostrf(A1, ffNumber, 15, 2) + ' KB'
else if A1 < 100 then Result := floattostrf(A1, ffNumber, 15, 1) + ' KB'
else if A2 < 1 then Result := floattostrf(A1, ffNumber, 15, 0) + ' KB'
else if A2 < 10 then Result := floattostrf(A2, ffNumber, 15, 2) + ' MB'
else if A2 < 100 then Result := floattostrf(A2, ffNumber, 15, 1) + ' MB'
else if A3 < 1 then Result := floattostrf(A2, ffNumber, 15, 0) + ' MB'
else if A3 < 10 then Result := floattostrf(A3, ffNumber, 15, 2) + ' GB'
else if A3 < 100 then Result := floattostrf(A3, ffNumber, 15, 1) + ' GB'
else Result := floattostrf(A3, ffNumber, 15, 0) + ' GB';
Result := Result + ' (' + floattostrf(A, ffNumber, 15, 0) + ' bytes)';
end;
这可能已经足够了,但还有什么更好的吗?
最佳答案
查看以下函数,全部在shlwapi library .
-
StrFormatByteSizeA
(双字参数) -
StrFormatByteSizeW
(Int64 参数) -
StrFormatByteSize64
(在Unicode模式下,真的是StrFormatByteSizeW
) -
StrFormatByteSizeEx
(Vista SP2;可以控制舍入)
其中任何一个都会为您提供所需显示格式的第一部分。检查文档或编写您自己的测试,以确认它们给出了您所期望的关于一兆字节是由 1000 还是 1024 KB 组成的转换。对于显示格式的第二部分,您可以从另一个 Stack Overflow 问题的答案开始:
- How to convert int to currency? (他实际上是在问如何插入逗号,而不是专门针对金钱。)
但也许这个问题是错误的途径,因为那里的所有建议以及 FloatToStrF
都在 Int64
的上限处失败。您会丢失一些字节,但我认为这些字节非常重要,因为该显示格式中的第二个值的目的是提供一个准确的数字。
一旦你有了所有的碎片,把它们粘在一起。我在这里使用了一个假设的 IntToStrCommas
函数,如果您想将其实现为 FloatToStrF
,请继续。
function BytesToDisplay(const num: Int64): string;
var
// If GB is the largest unit available, then 20 characters is
// enough for "17,179,869,183.99 GB", which is MaxUInt64.
buf: array[0..20] of Char;
begin
if StrFormatByteSize64(num, buf, Length(buf)) = nil then
raise EConvertError.CreateFmt('Error converting %d', [num]);
Result := Format('%s (%s bytes)', [buf, IntToStrCommas(num)]);
end;
关于像 Windows 一样显示字节数的 Delphi 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1285979/