1. Home
  2. Computing & Technology
  3. Delphi Programming

Formatting a File Size in Bytes for Display
Convert Bytes to String using Delphi

By , About.com Guide

When working with files from Delphi you might want to display the size of a file to the user in a Explorer-like format where the file size is not displayed in bytes - but the display depends on the size of the actual file.

To most users "45678123 b" is confusing - where "43.56 MB" is much more user friendly.

Format Byte Size to String

A custom Delphi function, FormatByteSize, converts a byte value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.
//Format file byte size
function FormatByteSize(const bytes: Longint): string;
const
  B = 1; //byte
  KB = 1024 * B; //kilobyte
  MB = 1024 * KB; //megabyte
  GB = 1024 * MB; //gigabyte
begin
  if bytes > GB then
    result := FormatFloat('#.## GB', bytes / GB)
  else
    if bytes > MB then
      result := FormatFloat('#.## MB', bytes / MB)
    else
      if bytes > KB then
        result := FormatFloat('#.## KB', bytes / KB)
      else
        result := FormatFloat('#.## bytes', bytes) ;
end;

Delphi tips navigator:
» Create a Custom Message Dialog with Standard Windows Icons using Delphi
« Controlling the Number of a Delphi application Instances on a Terminal Server

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2008 Tips
  7. Formatting a File Size in Bytes for Display - Convert Bytes to String using Delphi

©2009 About.com, a part of The New York Times Company.

All rights reserved.