Skip to content

Commit dfe02ba

Browse files
committed
Improve formatting of bytes
1 parent ce39595 commit dfe02ba

2 files changed

Lines changed: 16 additions & 20 deletions

File tree

FlashpointInstaller/src/Common.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -394,18 +394,16 @@ public static long GetTotalSize(TreeView sourceTree)
394394
// Formats bytes as a human-readable string
395395
public static string GetFormattedBytes(long bytes)
396396
{
397-
if (Math.Abs(bytes) >= 1000000000)
398-
{
399-
return (Math.Truncate((double)bytes / 100000000) / 10).ToString("N1") + "GB";
400-
}
401-
else if (Math.Abs(bytes) >= 1000000)
402-
{
403-
return (Math.Truncate((double)bytes / 100000) / 10).ToString("N1") + "MB";
404-
}
405-
else
397+
string[] units = new[] { " bytes", "KB", "MB", "GB" };
398+
int i = units.Length;
399+
400+
while (--i >= 0)
406401
{
407-
return (Math.Truncate((double)bytes / 100) / 10).ToString("N1") + "KB";
402+
double unitSize = Math.Pow(1024, i);
403+
if (bytes >= unitSize) return (Math.Floor(bytes / unitSize * 10) / 10).ToString("N1") + units[i];
408404
}
405+
406+
return "0 bytes";
409407
}
410408
}
411409
}

FlashpointManager/src/Common.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -526,18 +526,16 @@ public static long GetTotalSize(TreeView sourceTree)
526526
// Formats bytes as a human-readable string
527527
public static string GetFormattedBytes(long bytes)
528528
{
529-
if (Math.Abs(bytes) >= 1000000000)
530-
{
531-
return (Math.Truncate((double)bytes / 100000000) / 10).ToString("N1") + "GB";
532-
}
533-
else if (Math.Abs(bytes) >= 1000000)
534-
{
535-
return (Math.Truncate((double)bytes / 100000) / 10).ToString("N1") + "MB";
536-
}
537-
else
529+
string[] units = new[] { " bytes", "KB", "MB", "GB" };
530+
int i = units.Length;
531+
532+
while (--i >= 0)
538533
{
539-
return (Math.Truncate((double)bytes / 100) / 10).ToString("N1") + "KB";
534+
double unitSize = Math.Pow(1024, i);
535+
if (Math.Abs(bytes) >= unitSize) return (Math.Floor(bytes / unitSize * 10) / 10).ToString("N1") + units[i];
540536
}
537+
538+
return "0 bytes";
541539
}
542540
}
543541
}

0 commit comments

Comments
 (0)