How to Pretty Format a Number as File Size in C#, PHP and Delphi

This function will pretty format a given number as file size, for example, convert 1000000 to 1MB, 3523 to 3k and so on.

By Tim TrottC# ASP.Net MVC • January 24, 2009

Pretty Format a Number as File Size in C#

This short snippet can be used to pretty format a number of a file size (in bytes) into a pretty string that includes file size metric. This snippet is a modified version of the first posting which has been refactored by Ben Laan (see comments below). The original script was copied from some other website quite a while ago, cannot remember where from, but I have used it extensively and thought I would share this useful method. If you know who the original author is please let me know.

C#
public string FormatBytes(long bytes)
{
  const int scale = 1024;
  string[] orders = new string[] { "GB", "MB", "KB", "Bytes" };
  long max = (long)Math.Pow(scale, orders.Length - 1);

  foreach (string order in orders)
  {
    if ( bytes > max )
      return string.Format("{0:##.##} {1}", decimal.Divide( bytes, max ), order);

    max /= scale;
  }
  return "0 Bytes";
}

The original code:

C#
public string FormatBytes(int Bytes)
{
  string filesize;
  if (Bytes >= 1073741824)
  {
    decimal size = decimal.Divide(Bytes, 1073741824);
    filesize = string.Format("{0:##.##} GB", size);
  }
  else if (Bytes >= 1048576)
  {
    decimal size = decimal.Divide(Bytes, 1048576);
    filesize = string.Format("{0:##.##} MB", size);
  }
  else if (Bytes >= 1024)
  {
    decimal size = decimal.Divide(Bytes, 1024);
    filesize = string.Format("{0:##.##} KB", size);
  }
  else if (Bytes > 0 &amp; Bytes < 1024)
  {
    decimal size = Bytes;
    filesize = string.Format("{0:##.##} Bytes", size);
  }
  else
  {
    filesize = "0 Bytes";
  }
  return filesize;
}

Pretty Format a Number as File Size in PHP

Code to pretty format a number as file size

php
function formatbytes($val, $digits = 3, $mode = "SI", $bB = "B")
{ 
  $si = array("", "k", "M", "G", "T", "P", "E", "Z", "Y");
  $iec = array("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi");

  switch(strtoupper($mode)) 
  {
      case "SI" : $factor = 1000; $symbols = $si; break;
      case "IEC" : $factor = 1024; $symbols = $iec; break;
      default : $factor = 1000; $symbols = $si; break;
  }

  switch($bB) 
  {
      case "b" : $val *= 8; break;
      default : $bB = "B"; break;
  }
  
  for($i=0;$i<count($symbols)-1 && $val>=$factor;$i++)
      $val /= $factor;
  
  $p = strpos($val, ".");
  if($p !== false && $p > $digits) 
    $val = round($val);
  elseif($p !== false) 
    $val = round($val, $digits-$p);
  
  return round($val, $digits) . " " . $symbols[$i] . $bB;
}

Simply pass in an integer file size and it will return a value to 3 significant figures using SI notation. You can increase the number of figures by changing the second parameter in the call and the mode in the last two.

Example Formatting Number as File Size

php
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

Will output "somefile.txt: 219543 bytes"

php
$filename = 'somefile.txt';
echo $filename . ': ' . formatbytes(filesize($filename));

Will output "somefile.txt: 219 kB"

Pretty Format a Number as File Size in Delphi

Delphi Get File Size procedure will get the file size, in bytes, of a specified filename. Useful function for file-handing in Pascal.

pascal
function GetFileSize( FileName:string ): int64;
  var
    fh: integer;
    fi: TByHandleFileInformation;
  begin
  result := 0;
  fh := fileopen( FileName, fmOpenRead );
    try
    if GetFileInformationByHandle( fh, fi ) then
      begin
      result := fi.nFileSizeHigh;
      result := result shr 32 + fi.nFileSizeLow;
      end;
    finally
    fileclose( fh );
    end;
  end;

This function returns the filesize in bytes. If you want format that for users, such as showing megabytes or gigabytes you can use this function as well.

pascal
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;

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 11 comments. Why not join the discussion!

New comments for this post are currently closed.