Format the size in bytes

Feb 26, 2006

Earlier today, I posted a method that returns the total size of a directory, including all subdirectories. It returns the bytes and not kilobytes, megabytes or gigabytes, so I write a little formatting method to do just that.

private string SizeFormat(float size, string formatString)
{
    if (size < 1024)
        return size.ToString(formatString) + "bytes";

    if (size < Math.Pow(1024, 2))
        return (size / 1024).ToString(formatString) + " kb";

    if (size < Math.Pow(1024, 3))
        return (size / Math.Pow(1024, 2)).ToString(formatString) + " mb";

    if (size < Math.Pow(1024, 4))
        return (size / Math.Pow(1024, 3)).ToString(formatString) + " gb";

    return size.ToString(formatString);
}

The method take a size and a formatString parameter. The formatString parameter is for the formatting of the numbers themselves. You can format them to contain decimals or separators or whatever you please. This is how to call the method so it returns decimals:

SizeFormat(3210540, "N")

This method call returns this string: "3,14 MB"

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (3) -

 Jakob Christensen
Jakob Christensen
2/28/2006 12:10:22 PM #

Actually, I believe the right numbers ought to be 1024, 1024^2, 1024^3, ...

I may be wrong Wink

Mads Kristensen
Mads Kristensen
3/1/2006 1:13:30 PM #

Of course Jakob. My bad. I'll correct the error when I get home from work tonight.

 Mads Kristensen
Mads Kristensen
3/1/2006 3:01:43 PM #

The example is now fixed thanks to Jakob's eye for detail. It took me a while to find the Math.Pow() function. I get an overflow when I do 1024*1024*1024*1024 and the ^ operater doesn't do the job.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.