分享一个Byte KB MB GB 单位转换方法 从《C#本质论第三版》
static public string FormatBytes(long bytes)
{
string[] magnitudes =
new string[] { "GB", "MB", "KB", "Bytes" };
long max = (long)Math.Pow(1024, magnitudes.Length);
return string.Format("{1:##.##} {0}",
magnitudes.FirstOrDefault(
magnitude =>bytes>(max/=1024))??"0 Bytes",
(decimal)bytes/(decimal)max ).Trim();
}
magnitudes.FirstOrDefault( magnitude =>bytes>(max/=1024))
这一步是精髓,max 一开始就是有1024GB大小,bytes>(max/=1024)则是表示当前字节大小大于每个单位数值为1时的大小,
就返回当前单位,并且作为format的{0}的参数填充。
(decimal)bytes/(decimal)max 则是 算出 bytes含有几个这样单位数值的大小,并保留2为小数展示作为{1}的参数。
测试代码:
Console.WriteLine(FormatBytes(1024 ));
Console.WriteLine(FormatBytes(1024 * 1024));
Console.WriteLine(FormatBytes(1024 * 1024*1024));
Console.WriteLine(FormatBytes(1024L * 1024 * 1024 * 1024));
注意数值溢出,加上L表示是long类型的数值类型。
结果:

浙公网安备 33010602011771号