我正在使用以下代码将字节转换为易读的文件大小。但是,它没有给出准确的结果。
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]);
}
}
使用方法:
FileSizeHelper.GetHumanReadableFileSize(63861073920);
它返回 59.48 GB
但如果我使用谷歌转换器将相同的字节转换,它会给出63.8GB
。
有什么想法是代码有什么问题吗?
谷歌截图:
@René Vogt 和 @bashis 感谢解释。最终使用以下代码使其工作:
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]);
}
}
63861073920 bytes to gib
- user4003407