只是想知道.NET提供了一种干净的方法:

int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
    y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
    y = string.Format("{0:n1} KB", x / 1024f);
}

推荐答案

这里有一个相当简明的方法来实现这一点:

static readonly string[] SizeSuffixes = 
                   { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
    if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } 
    if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

    // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
    int mag = (int)Math.Log(value, 1024);

    // 1L << (mag * 10) == 2 ^ (10 * mag) 
    // [i.e. the number of bytes in the unit corresponding to mag]
    decimal adjustedSize = (decimal)value / (1L << (mag * 10));

    // make adjustment when the value is large enough that
    // it would round up to 1000 or more
    if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
    {
        mag += 1;
        adjustedSize /= 1024;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", 
        adjustedSize, 
        SizeSuffixes[mag]);
}

下面是我建议的原始实现,可能稍微慢一点,但更容易遵循:

static readonly string[] SizeSuffixes = 
                  { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } 

    int i = 0;
    decimal dValue = (decimal)value;
    while (Math.Round(dValue, decimalPlaces) >= 1000)
    {
        dValue /= 1024;
        i++;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

要记住一件事——在SI符号中,"kilo"通常使用小写的k,而所有较大的单位都使用大写字母.Windows使用KB、MB、GB,所以我已经使用了上面的KB,但是您可以考虑KB.

.net相关问答推荐

如何手动注入依赖注入

如何使用 awslocal 通过 localstack 中的 cloudwatch events/eventbridge 触发 lambda

使用 PostAsJsonAsync C# 时出现错误请求

无法加载文件或程序集 Microsoft.Extensions.DependencyInjection.Abstractions,版本 = 1.1.0.0

为什么 .Contains 慢?通过主键获取多个实体的最有效方法?

SubscribeOn 和 ObserveOn 有什么区别

托管和非托管代码、内存和大小有什么区别?

是否有用于 Windows / C# 开发的可嵌入 Webkit 组件?

您可以在 C# 代码中捕获本机异常吗?

.NET 中是否有可序列化的通用键/值对类?

Dapper 是否支持 SQL 2008 表值参数?

一个接口是否应该继承另一个接口

如何从 .NET 读取 PEM RSA 私钥

将日期时间转换为时间跨度

自创建数据库以来,支持ApplicationDbContext上下文的模型已更改

例外:不支持 URI 格式

如何在 Dapper.Net 中编写一对多查询?

从 Visual Studio 2015 发布 - 允许不受信任的证书

Roslyn 编译代码失败

MultipleActiveResultSets=True 还是多个连接?