«

将字节(Byte)单位的文件大小数值,自动转换为更易读的单位格式(B/KB/MB/GB),并对结果进行格式化处理(移除末尾多余的 ".00")

hujiato 发布于 阅读:90 编程


代码:

public static string GetByteLabel(double limit)
{
    string size;
    if (limit < 0.1 * 1024)  // 小于0.1KB,显示为B
    {
        size = $"{limit:F2}B";
    }
    else if (limit < 0.1 * 1024 * 1024)  // 小于0.1MB,显示为KB
    {
        size = $"{limit / 1024:F2}KB";
    }
    else if (limit < 0.1 * 1024 * 1024 * 1024)  // 小于0.1GB,显示为MB
    {
        size = $"{limit / (1024 * 1024):F2}MB";
    }
    else  // 其他情况显示为GB
    {
        size = $"{limit / (1024 * 1024 * 1024):F2}GB";
    }

    // 处理小数点后两位为00的情况
    int index = size.IndexOf('.');
    if (index != -1 && index + 3 <= size.Length)
    {
        string dou = size.Substring(index + 1, 2);
        if (dou == "00")
        {
            return size.Substring(0, index) + size.Substring(index + 3);
        }
    }

    return size;
}

调用:

Console.WriteLine(GetByteLabel(50));        // 输出 "50B"
Console.WriteLine(GetByteLabel(2048));      // 输出 "2.00KB"
Console.WriteLine(GetByteLabel(1500000));   // 输出 "1.43MB"

文章目录