Hello,
I want to convert a single number of bytes, into a file size (that has .KB, .MB and .GB).
If the number is 0, I don't want to have any unit. If the number is exactly divisible by a multiple of 1024 (not a floating point), then I will print: x . Otherwise, I want to print a floating point with one degree precision.
I made some code that seems to work well, but it's very cumbersome. I'm looking into ways I could make my function cleaner/more efficient please, it's honestly VERY ugly:
char *
calculateSize( off_t size )
{
char *result = (char *) malloc(sizeof(char) * 20);
static int GB = 1024 * 1024 * 1024;
static int MB = 1024 * 1024;
static int KB = 1024;
if (size >= GB) {
if (size % GB == 0)
sprintf(result, "%d GB", size / GB);
else
sprintf(result, "%.1f GB", (float) size / GB);
}
else if (size >= MB) {
if (size % MB == 0)
sprintf(result, "%d MB", size / MB);
else
sprintf(result, "%.1f MB", (float) size / MB);
}
else {
if (size == 0) {
result[0] = '0';
result[1] = '\0';
}
else {
if (size % KB == 0)
sprintf(result, "%d KB", size / KB);
else
sprintf(result, "%.1f KB", (float) size / KB);
}
}
return result;
}
I would really appreciate if someone has a better way to achieve the same result please.
Thank you very much,
Jary