Skip to content

Commit 098e376

Browse files
committed
fix: 修复 GetBytesSize 方法中大数值单位转换错误
原循环逻辑在 size 等于 1024 时会提前返回 "1024B",而不是正确的 "1KB"。同时,对于超过 PB 单位的极大值处理不当。 重构循环条件,确保正确进行单位换算,并优化输出格式,保留两位小数并去除尾部零。
1 parent ee10837 commit 098e376

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Runtime/Utility/Utility.File.cs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public static partial class Utility
88
[UnityEngine.Scripting.Preserve]
99
public static class File
1010
{
11-
private static readonly string[] UnitList = new[] {"B", "KB", "MB", "GB", "TB", "PB"};
11+
private static readonly string[] UnitList = new[] { "B", "KB", "MB", "GB", "TB", "PB" };
1212

1313
/// <summary>
1414
/// 获取字节大小
@@ -18,17 +18,23 @@ public static class File
1818
[UnityEngine.Scripting.Preserve]
1919
public static string GetBytesSize(long size)
2020
{
21-
foreach (var unit in UnitList)
21+
double dSize = size;
22+
int unitIndex = 0;
23+
24+
while (dSize >= 1024 && unitIndex < UnitList.Length - 1)
2225
{
23-
if (size <= 1024)
24-
{
25-
return size + unit;
26-
}
26+
dSize /= 1024;
27+
unitIndex++;
28+
}
2729

28-
size /= 1024;
30+
if (unitIndex == 0)
31+
{
32+
return dSize + UnitList[unitIndex];
2933
}
3034

31-
return size + UnitList[0];
35+
// 格式化为保留两位小数,但去除尾部不必要的零
36+
string formattedSize = dSize.ToString("F2").TrimEnd('0').TrimEnd('.');
37+
return formattedSize + UnitList[unitIndex];
3238
}
3339
}
3440
}

0 commit comments

Comments
 (0)