C - 在 999 以上加小数位和四舍五入

标签 c

我有一个与文件大小相对应的整数(以字节为单位)。返回 400 的 int 大小为 400 字节,返回 10400 的 int 大小为 10.4 KB。我想要做的是将 10400 之类的 int 转换为 10.4,并且还可以区分 10.4 KB、10.4 MB 或 10.4 GB。因为 10400 是 10.4 KB,10400000 是 10.4 MB,10400000000 是 10.4 GB。有人对此有解决方案吗?

最佳答案

您可以使用:

void pretty_bytes(char* buf, uint bytes)
{
    const char* suffixes[7];
    suffixes[0] = "B";
    suffixes[1] = "KB";
    suffixes[2] = "MB";
    suffixes[3] = "GB";
    suffixes[4] = "TB";
    suffixes[5] = "PB";
    suffixes[6] = "EB";
    uint s = 0; // which suffix to use
    double count = bytes;
    while (count >= 1024 && s < 7)
    {
        s++;
        count /= 1024;
    }
    if (count - floor(count) == 0.0)
        sprintf(buf, "%d %s", (int)count, suffixes[s]);
    else
        sprintf(buf, "%.1f %s", count, suffixes[s]);
}

Source

如果你不想使用缓冲区:

static const char *humanSize(uint64_t bytes)
{
    char *suffix[] = {"B", "KB", "MB", "GB", "TB"};
    char length = sizeof(suffix) / sizeof(suffix[0]);

    int i = 0;
    double dblBytes = bytes;

    if (bytes > 1024) {
        for (i = 0; (bytes / 1024) > 0 && i<length-1; i++, bytes /= 1024)
            dblBytes = bytes / 1024.0;
    }

    static char output[200];
    sprintf(output, "%.02lf %s", dblBytes, suffix[i]);
    return output;
}

关于C - 在 999 以上加小数位和四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49766514/

相关文章:

c - spoj 阶乘(超过时间限制错误)。我怎样才能改进我的解决方案?

c - 在结构中保存文件指针时出现段错误

c - 如何释放这段 C 代码中分配的内存?

c - 为什么我的代码在 Visual Studio 中返回 -nan,但在 Linux 中不返回?

c - 补码对 Fletcher 的校验和有影响吗?

c++ - 将 goto 标签暴露给符号表

c - BST 树到 AVL

c - 使用 fscanf 从输入文件中逐行读取

c - 在 C 中搜索整数数组中的最大数字

c - 使用C语言写入文本文件