J'ai cherché une fonction comme celle là longtemp, c'était pourtant simple (une fois que l'on voit la solution des autres )
function SizeToStr(Sz: int64): string; resourcestring strMinSize = '0 Octets'; strKo = '%s Ko'; strMo = '%s Mo'; strGo = '%s Go'; strOct = '%s Octets'; const cstFloatFmt = '#.##'; cstOneKo = 1024; cstOneMo = cstOneKo * 1024; cstOneGo = cstOneMo * 1024; begin Result := strMinSize; if (Sz = 0) then Exit; if (Sz <= cstOneKo) then begin Result := Format(strOct, [FormatFloat(cstFloatFmt, Sz)]); Exit; end; if (Sz <= cstOneMo) then begin Result := Format(strKo, [FormatFloat(cstFloatFmt, Sz / cstOneKo)]); Exit; end; if (Sz <= cstOneGo) then begin Result := Format(strMo, [FormatFloat(cstFloatFmt, Sz / (cstOneMo))]); Exit; end; Result := Format(strGo, [FormatFloat(cstFloatFmt, Sz / (cstOneGo))]); end;
une alternative consiste à utiliser :
function StrFormatByteSize(dw: DWORD; szBuf: PChar; uiBufSize: UINT):PChar; stdcall; external 'shlwapi.dll' name 'StrFormatByteSizeA'; function StrFormatKBSize(qdw: LONGLONG; szBuf: PChar; uiBufSize: UINT):PChar; stdcall; external 'shlwapi.dll' name 'StrFormatKBSizeA';
Et on appelle ces fonction comme ça :
procedure TForm1.Button15Click(Sender: TObject); var arrSize: array[0..255] of Char; begin {même formatage que statusbar dans Explorer} StrFormatByteSize(70846, arrSize, Length(arrSize)-1); ShowMessage(Trim(arrSize));
{même formatage que la colonne taille d'Explorer en mode détail} StrFormatKBSize(70846, arrSize, Length(arrSize)-1); ShowMessage(Trim(arrSize)); end;
remarque : shlwapi.dll doit etre installé dans MS Windows (en installant IE5 ou plus) et justement cette façon de faire, me gene dans la mesure ou, on est dépendant de dll qui peuvent changer.