public static class Extensions
{
public static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
public static string AppendSizeSuffix(this Int64 value, int decimalPlaces = 0)
{
if (value < 0) { return "-" + AppendSizeSuffix(-value); }
if (value == 0) { return "0.0 bytes"; }
int mag = (int)Math.Log(value, 1024);
decimal adjustedSize = (decimal)value / (1L << (mag * 10));
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}
var rounded = string.Format("{0:n" + decimalPlaces + "}", adjustedSize);
return $"{rounded} {SizeSuffixes[mag]}";
}
}
Comments