Hope someone can figure this one out.
I'm using this to display the filesizes of several files in a folder...
number_format (round (filesize($currentfile) /1048576)) . "mb"
...which displays my file names like this:
27mb
35mb
10mb
etc.
But, if the filesize is less than 1mb, it displays onscreen as:
0mb
How can I modify the PHP so that if it encounters a 250k file for example, it shows displays as ".25mb"?
Thanks in advance.
Well you just need to check if it is below 1MB and handle it differently.
number_format (filesize($currentfile) / 1048576, (filesize($currentfile) < 1048576 ? 2 : 0)) . "mb"
Well, you'd need to remove the round
call, it's making integers:
number_format (filesize($currentfile) /1048576, 2) . "mb"
Which will give:
27mb
35mb
10.25mb < if it's really 10.25mb
0.25mb
if((filesize($currentfile) /1048576) >= 1)
number_format (round (filesize($currentfile) /1048576), 1) . "mb";
else
number_format (filesize($currentfile) /1048576, 2) . "mb"
More robust:
function fsize_fmt($bytes, $precision=2) {
$unit = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($x=0; $bytes>=1024 && $x<count($unit); $x++) { $bytes /= 1024; }
return round($bytes, $precision) . ' ' . $unit[$x];
}
It's better to create a function so you can reuse it elsewhere in your app, then if you decide to change the formatting or something later on you can do it easily in one place. I'm sure there's something more elegant out there, but for the sake of simplicity here's one I just whipped up:
function pretty_size($bytes, $dec_places = 1) {
$total = $bytes / 1024 / 1024 / 1024 / 1024;
$unit = 'TB';
if( $total < 1 ) {
$total = $bytes / 1024 / 1024 / 1024;
$unit = 'GB';
}
if( $total < 1 ) {
$total = $bytes / 1024 / 1024;
$unit = 'MB';
}
if( $total < 1 ) {
$total = $bytes / 1024;
$unit = 'KB';
}
if( $total < 1 ) {
$total = $bytes;
$unit = 'bytes';
}
return array(number_format($total, $dec_places), $unit);
}
You can test it out using this:
$numbers = array(
89743589734434,
39243243223,
3456544,
12342443,
324324,
4233,
2332,
32
);
foreach( $numbers as $n ) {
$size = pretty_size($n);
echo $size[0] . ' ' . $size[1] . '<br />';
}
The above code will produce this:
81.6 TB
36.5 GB
3.3 MB
11.8 MB
316.7 KB
4.1 KB
2.3 KB
32.0 bytes
Of course, if you really want to limit the display to just megabytes, you can alter the function accordingly. Easy enough :)