Skip to content

Instantly share code, notes, and snippets.

@dampee
Created March 16, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dampee/0f555a97fe8feb886ef5 to your computer and use it in GitHub Desktop.
Save dampee/0f555a97fe8feb886ef5 to your computer and use it in GitHub Desktop.
formats a number as filesize with GB, MB, KB or bytes
public class FileSize
{
public static string FormatBytes(string bytes, int scale = 1024)
{
long bytesNumber = Convert.ToInt64(bytes);
return FormatBytes(bytesNumber, scale);
}
public static string FormatBytes(long bytes, 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";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment