1 /// <summary> 2 /// 将字节转文件大小B KB MB GB 3 /// </summary> 4 /// <param name="fileSize">字节</param> 5 /// <returns></returns> 6 public static string GetSize(Nullable<long> fileSize) 7 { 8 double fileByte = 0.00; 9 string size = ""; 10 if (fileSize == null) 11 { 12 fileByte = 0.00; 13 } 14 else 15 { 16 fileByte = (double)fileSize*1.00; 17 } 18 19 if (fileByte < 0.1 * 1024) 20 { 21 // 小于0.1KB,则转化成B 22 size = $"{fileByte:F2}B"; 23 } 24 else if (fileByte < 0.1 * 1024 * 1024) 25 { 26 // 小于0.1MB,则转化成KB 27 size = $"{(fileByte / 1024):F2}KB"; 28 } 29 else if (fileByte < 0.1 * 1024 * 1024 * 1024) 30 { 31 // 小于0.1GB,则转化成MB 32 size = $"{(fileByte / (1024 * 1024)):F2}MB"; 33 } 34 else 35 { 36 // 其他转化成GB 37 size = $"{(fileByte / (1024 * 1024 * 1024)):F2}GB"; 38 } 39 40 string sizeStr = $"{size}"; // 转成字符串 41 int index = sizeStr.IndexOf("."); // 获取小数点处的索引 42 string dou = sizeStr.Substring(index + 1, 2); // 获取小数点后两位的值 43 if (dou == "00") 44 { 45 // 判断后两位是否为00,如果是则删除00 46 return sizeStr.Substring(0, index) + sizeStr.Substring(index + 3, 2); 47 } 48 return size; 49 }