title: Delphi Function to Display Number of Bytes as Windows Does
body: <p>This is a simple one (I think).</p>
  
  <p>Is there a system built in function, or a function that someone has created that can be called from Delphi, that will display a number of bytes (e.g. a filesize), the way Windows displays in a file's Properties box?</p>
  
  <p>e.g. This is how Windows property box displays various sizes: </p>
  
  <pre><code>539 bytes (539 bytes)
  35.1 KB (35,974 bytes)
  317 MB (332,531,365 bytes)
  2.07 GB (2,224,617,077 bytes)
  </code></pre>
  
  <p>The display is smart about using bytes, KB, MB or GB, and shows only 3 significant digits for the KB, MB and GB.  It then follows that by displaying the exact number of bytes in parenthesis with commas separating the thousands. It is a very nice display, well thought out.</p>
  
  <p>Does anyone know of such a function?</p>
  
  <hr>
  
  <p>Edit: I'm very surprised there wasn't a function for this.</p>
  
  <p>Thanks for your helpful ideas. I've come up with this, which seems to work:</p>
  
  <pre><code>function BytesToDisplay(A:int64): string;
  var
    A1, A2, A3: double;
  begin
    A1 := A / 1024;
    A2 := A1 / 1024;
    A3 := A2 / 1024;
    if A1 &lt; 1 then Result := floattostrf(A, ffNumber, 15, 0) + ' bytes'
    else if A1 &lt; 10 then Result := floattostrf(A1, ffNumber, 15, 2) + ' KB'
    else if A1 &lt; 100 then Result := floattostrf(A1, ffNumber, 15, 1) + ' KB'
    else if A2 &lt; 1 then Result := floattostrf(A1, ffNumber, 15, 0) + ' KB'
    else if A2 &lt; 10 then Result := floattostrf(A2, ffNumber, 15, 2) + ' MB'
    else if A2 &lt; 100 then Result := floattostrf(A2, ffNumber, 15, 1) + ' MB'
    else if A3 &lt; 1 then Result := floattostrf(A2, ffNumber, 15, 0) + ' MB'
    else if A3 &lt; 10 then Result := floattostrf(A3, ffNumber, 15, 2) + ' GB'
    else if A3 &lt; 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;
  </code></pre>
  
  <p>This is probably good enough, but is there anything better?</p>