Displays the file size in readable form, in specified or autodetected units.
1 2 3 4 5 6 7 |
var fileSize: int64; precision: integer; begin fileSize:= 8784641646; formatBytes(fileSize, sfAuto, 2); end; |
Options
size - file size in bytes
formatType - defines in what units the result will be displayed (byte, MB, GB, TB, Auto)
If sfAuto is specified, the unit will depend on the file size, for example, if the size is more than a megabyte, but less than a gigabyte, the result will be displayed in megabytes
precision - the precision of the result, i.e. the number of digits after the decimal point.
Result
Formatted file size string:
formatBytes(fileSize, sfAuto, 2) - result: 8.18 GB
formatBytes(fileSize, sfMB, 2) - result: 8 377.69 MB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
type TSizeFormatType = (sfByte, sfKB, sfMB, sfGB, sfTB, sfAuto); function formatBytes(size: Int64; formatType: TSizeFormatType; precision: integer): string; var D: double; const FormatArray: array [TSizeFormatType] of string = ('bytes', 'KB', 'MB', 'GB', 'TB', ''); function BytesToKB(Size: Int64): Int64; begin Result := Size div 1024; if (Size mod 1024 <> 0) then Result := Result + 1; end; begin Result := ''; D := Size; Case FormatType of sfAuto: begin FormatType := sfKB; D := BytesToKB(Size); while (D > 1024) and (FormatType < sfAuto) do begin D := D / 1024; FormatType := Succ(FormatType); end; end; sfByte: D := Size; sfKB: D := BytesToKB(Size); sfMB: D := BytesToKB(Size) / 1024; sfGB: D := BytesToKB(Size) / 1024 / 1024; sfTB: D := BytesToKB(Size) / 1024 / 1024 / 1024; end; if FormatType <= sfKB then Precision := 0; Result := Format('%.'+ IntToStr(Precision) + 'n ' + FormatArray[FormatType], [D]); end; |