I was refactoring some old code and came across the following line of code to convert bytes to GB.
decimal GB = KB / 1024 / 1024 / 1024;
Is
This is a little improvement of the good JLopez's answer. Here you can choose to have or not the units indication and the kilo unit is written with the lowercase "k" (the uppercase one is for Kelvin)
//note: this is the JLopez answer!!
///
/// Return size in human readable form
///
/// Size in bytes
/// Includes measure unit (default: false)
/// Readable value
public static string FormatBytes(long bytes, bool useUnit = false)
{
string[] Suffix = { " B", " kB", " MB", " GB", " TB" };
double dblSByte = bytes;
int i;
for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024)
{
dblSByte = bytes / 1024.0;
}
return $"{dblSByte:0.##}{(useUnit ? Suffix[i] : null)}";
}