41 lines
1.3 KiB
C#
Executable File
41 lines
1.3 KiB
C#
Executable File
namespace DotBased.Utilities;
|
|
|
|
/// <summary>
|
|
/// Suffix functions for multiple types of values
|
|
/// </summary>
|
|
public static class Suffix
|
|
{
|
|
private static readonly string[] SizeSuffixes =
|
|
["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
|
|
|
/// <summary>
|
|
/// Converts the bytes to the memory suffix.
|
|
/// </summary>
|
|
/// <param name="bytes">The bytes to convert</param>
|
|
/// <param name="decimalPlaces">How manny decimal places will be placed</param>
|
|
/// <returns>The suffixed bytes in the correct format</returns>
|
|
public static string BytesToSizeSuffix(long bytes, int decimalPlaces = 1)
|
|
{
|
|
if (decimalPlaces < 0) decimalPlaces = 1;
|
|
|
|
if (bytes == 0)
|
|
return $"{0.ToString($"N{decimalPlaces}")} bytes";
|
|
|
|
var negative = bytes < 0;
|
|
var absBytes = (ulong)(negative ? -bytes : bytes);
|
|
|
|
var mag = (int)Math.Log(absBytes, 1024);
|
|
var adjustedSize = absBytes / Math.Pow(1024, mag);
|
|
|
|
if (Math.Round(adjustedSize, decimalPlaces) >= 1000 && mag < SizeSuffixes.Length - 1)
|
|
{
|
|
mag++;
|
|
adjustedSize /= 1024;
|
|
}
|
|
|
|
var format = $"N{decimalPlaces}";
|
|
var result = $"{adjustedSize.ToString(format)} {SizeSuffixes[mag]}";
|
|
|
|
return negative ? "-" + result : result;
|
|
}
|
|
} |