Converting bytes to GB in C#?

前端 未结 13 965
孤城傲影
孤城傲影 2020-12-23 12:09

I was refactoring some old code and came across the following line of code to convert bytes to GB.

decimal GB = KB / 1024 / 1024 / 1024;

Is

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 12:23

    This is a little improvement of the good JLopez's answer. Here you can choose to have or not the units indication and the kilo unit is written with the lowercase "k" (the uppercase one is for Kelvin)

    //note: this is the JLopez answer!!
    /// 
    /// Return size in human readable form
    /// 
    /// Size in bytes
    /// Includes measure unit (default: false)
    /// Readable value
    public static string FormatBytes(long bytes, bool useUnit = false)
        {
            string[] Suffix = { " B", " kB", " MB", " GB", " TB" };
            double dblSByte = bytes;
            int i;
            for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024)
            {
                dblSByte = bytes / 1024.0;
            }
            return $"{dblSByte:0.##}{(useUnit ? Suffix[i] : null)}";
        }
    

提交回复
热议问题