Willcode4cash icon

Convert file lengths to MB, GB, etc

Willcode4cash | PRO | 06/23/17 03:24:04 PM UTC | 0 ⭐ | 273 👁️ | Never ⏰ | []
C# |

660 B

|

None

|

0 👍

/

0 👎

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