function humanFileSize($size)
{
if ($size >= 1073741824) {
$fileSize = round($size / 1024 / 1024 / 1024,1) . 'GB';
} elseif ($size >= 1048576) {
$fileSize = round($size / 1024 / 1024,1) . 'MB';
} elseif($size >= 1024) {
$fileSize = round($size / 1024,1) . 'KB';
} else {
$fileSize = $size . ' bytes';
}
return $fileSize;
}
... works great except: I can't manually choose in what format I need to display, say i want to show in MB only whatever the file size is. Currently if its in the GB range, it would only show in GB.
Also, how do I limit the decimal to 2?
I'm using this method:
works great in o(1).
Try something like this:
Here is a working function managing till Yottabyte:
}
To expand on Vaidas' answer, here's how you should do it to account for the new IEC standards:
Technically, according to the specifications for storage devices and such you should use the metric system as default (that's why Google converter shows kB -> MB as mod 1000 instead of 1024).
There is great example by Jeffrey Sambells:
I wanted a function that returned filesizes like Windows does, and surprisingly I could find none at all. Even worse, some here and elsewhere are broken in that they assume 1KB = 1000B.
So I coded one! Plus two helper functions. Here they are:
Usage is as simple as
humanSize(123456789)
.