Skip to content

Instantly share code, notes, and snippets.

@SamWM
Created December 22, 2009 16:27
Show Gist options
  • Select an option

  • Save SamWM/261833 to your computer and use it in GitHub Desktop.

Select an option

Save SamWM/261833 to your computer and use it in GitHub Desktop.
FormatFileSize
private string FormatFileSize(long size)
{
return FormatFileSize((double)size);
}
private string FormatFileSize(double size)
{
string output = string.Empty;
string append = string.Empty;
string format = string.Empty;
if (size < 1000)
{
format = "b"; append = " bytes";
}
else if (size > 999 && size < 1000000)
{
format = "kb"; append = " kb";
}
else
{
format = "mb"; append = " mb";
}
if (format == "b") output = size + append;
if (format == "kb")
{
// divide by 1024 to get the size in kb
size = size / 1024;
// multiply by 10 to the power of 2
size = size * Math.Pow(10, 2);
// round up/down the new file size, and divide to remove the power and return the correct value
size = Math.Round(size) / Math.Pow(10, 2);
output = size + append;
}
if (format == "mb")
{
// divide by 1024 twice to get the size in mb
size = size / 1024 / 1024;
// multiply by 10 to the power of 2
size = size * Math.Pow(10, 2);
// round up/down the new file size, and divide to remove the power and return the correct value
size = Math.Round(size) / Math.Pow(10, 2);
output = size + append;
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment