Skip to content

Instantly share code, notes, and snippets.

@gregmac
Created August 10, 2021 18:17
Show Gist options
  • Save gregmac/93d1f2a75ab5c9bdc8badbe8bf2163b8 to your computer and use it in GitHub Desktop.
Save gregmac/93d1f2a75ab5c9bdc8badbe8bf2163b8 to your computer and use it in GitHub Desktop.
private static string[] ByteUnits = new string[] { "B", "KB", "MB", "GB", "TB" };
/// <inheritdoc cref="BytesToString(decimal, byte)"/>
public static string BytesToString(this int? value, byte decimals = 2) => BytesToString((decimal)value, decimals);
/// <summary>
/// Display a byte value with units, rounded up to nearest possible size unit.
/// </summary>
/// <param name="value">Number of bytes</param>
/// <param name="decimals">Number of decimal places to show</param>
/// <returns>The size as a string with units, such as <c>"2.2 MB"</c> or <c>"998.1 KB"</c></returns>
public static string BytesToString(this decimal? value, byte decimals = 2)
{
if (value == null) return null;
byte i;
for (i = 0; i < ByteUnits.Length - 1 && value >= 1024; i++) value /= 1024m;
return $"{Math.Round(value.Value, decimals)} {ByteUnits[i]}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment