Skip to content

Instantly share code, notes, and snippets.

@derantell
Last active August 29, 2015 14:02
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 derantell/5df4df934a1da2259f99 to your computer and use it in GitHub Desktop.
Save derantell/5df4df934a1da2259f99 to your computer and use it in GitHub Desktop.
Get formatted byte size from long value
public static string FriendlyFileSize( long size) {
const double @base = 1024d;
const string format = "{0:0.#} {1}";
if (size == 0L) {
return "0 b";
}
var magnitudes = new Dictionary<int, string> {
{0, "B" }, {1, "kB"}, {2, "MB"},
{3, "GB"}, {4, "TB"}, {5, "PB"},
{6, "EB"}, {7, "ZB"}, {8, "YB"}
};
var magnitude = Math.Min(8, (int) Math.Log(size, @base) );
var divider = Math.Pow(@base, magnitude);
var value = size/divider;
return string.Format(format, value, magnitudes[magnitude]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment