C - 在999以上添加小数位和round int

时间:2018-04-11 04:28:58

标签: 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。有人有解决方案吗?

1 个答案:

答案 0 :(得分:2)

您可以使用以下方式执行此操作:

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;
}