我有一个与文件大小相对应的整数(以字节为单位)。返回 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]);
}
如果你不想使用缓冲区:
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/