Last active
August 29, 2015 14:02
-
-
Save derantell/5df4df934a1da2259f99 to your computer and use it in GitHub Desktop.
Get formatted byte size from long value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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