Converting bytes to GB in C#?

前端 未结 13 922
孤城傲影
孤城傲影 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 12:18

        public static string BytesToString(this long bytes, string format = "#,##0.00") {
            var unitstr = new string[] { "B", "KB", "MB", "GB", "TB" };
            var bytesd = Convert.ToDouble(bytes);
            var unit = 0;
            while (bytesd / 1024D > 1 && unit < unitstr.Length) {
                unit++; bytesd /= 1024D;
            }
            return string.Format("{0:" + format + "}{1}", bytesd, unitstr[unit]);
        }
    

提交回复
热议问题