I am using the following code to convert bytes to human readable file size. But it's not giving accurate result.
public static class FileSizeHelper
{
static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
public static string GetHumanReadableFileSize(Int64 value)
{
if (value < 0) { return "-" + GetHumanReadableFileSize(-value); }
if (value == 0) { return "0.0 bytes"; }
int mag = (int)Math.Log(value, 1024);
decimal adjustedSize = (decimal)value / (1L << (mag * 10));
return string.Format("{0:n2} {1}", adjustedSize, SizeSuffixes[mag]);
}
}
Usage:
FileSizeHelper.GetHumanReadableFileSize(63861073920);
It returns 59.48 GB
But if I convert the same bytes using google converter it gives 63.8GB
.
Any idea what is wrong in the code?
Goolge screenshot:
@René Vogt and @bashis thanks for explanation. finally get it working using following code
public static class FileSizeHelper
{
static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
const long byteConversion = 1000;
public static string GetHumanReadableFileSize(long value)
{
if (value < 0) { return "-" + GetHumanReadableFileSize(-value); }
if (value == 0) { return "0.0 bytes"; }
int mag = (int)Math.Log(value, byteConversion);
double adjustedSize = (value / Math.Pow(1000, mag));
return string.Format("{0:n2} {1}", adjustedSize, SizeSuffixes[mag]);
}
}
There is always a little confusion about how to display bytes. Your code is correct if the result is what you are trying to achieve.
What you showed from Google is a decimal representation. So just as you say 1000m = 1km
, you can say 1000byte = 1kB
.
On the other hand, there is the binary representation where 1k = 2^10 = 1024
. These representations are called kibiBytes, Gibibytes etc.
Which representation you choose is up to you or the requirements of your customers. Just make obvious which you use to avoid confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With