Converting data size to a string

A simple little extension method to convert a size in bytes to a human readable value.

public static class DataSizeHelper
{
    public const long KiloBytes = 1024;
    public const long MegaBytes = KiloBytes * KiloBytes;
    public const long GigaBytes = KiloBytes * MegaBytes;
    public const long TeraBytes = KiloBytes * GigaBytes;

    public static string FormatBytes(this long bytes)
    {
        string label;
        double value = bytes;
        if (value < KiloBytes)
        {
            label = " Bytes";
        }
        else if (value < MegaBytes)
        {
            label = " KB";
            value = value / KiloBytes;
        }
        else if (value < GigaBytes)
        {
            label = " MB";
            value = value / MegaBytes;
        }
        else if (value < TeraBytes)
        {
            label = " GB";
            value = value / GigaBytes;
        }
        else
        {
            label = " TB";
            value = value / TeraBytes;
        }
        return Math.Round(value, 2) + label;
    }
}

And for fun here is a good page to help people understand Orders of Magnitude. With fun numbers like

  • 10,000,000,000,000 bits (1.25 terabytes) – capacity of a human being's functional memory
  • 3.4×1021 bits (0.36 zettabytes) – amount of information that can be stored in 1 gram of DNA
Posted by: Simon Cropp
Last revised: 26 Feb, 2012 09:30 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.