Reputation: 18520
I'm displaying how large a list of files are in a table using PHP. I'd like to display how big they are in megabytes instead of the default bytes. The problem I'm having is that I get extremely long decimals, which is impractical for this purpose.
Here's what I have so far:
print((filesize("../uploads/" . $dirArray[$index])) * .000000953674316 . " MB");
Which correctly converts the value, but changes, for example, 71 B
to 6.7710876436E-5 MB
.
I think the E-5 thing is like x10^-5
which would probably add up correctly, but is there a way I can cut off how many numbers it goes down to? If it displays as "00.00 MB" that's fine by me, most file are going to be much bigger than this test one.
Upvotes: 1
Views: 1055
Reputation: 44969
If you need other units, too, you might use this function I wrote years ago:
<?php
function human_filesize($size, $precision = 2)
{
$a_size = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$count = count($a_size) - 1;
$i = 0;
while ($size / 1024 >= 1 && $count >= $i) {
$size = $size / 1024;
$i++;
}
return round($size, $precision) . ' ' . $a_size[$i];
}
// =========
// USAGE
// =========
// Output: 34.35 MiB
echo human_filesize(filesize('file.zip'));
// Output: 34 MiB
echo human_filesize(filesize('file.zip'), 0);
// Output: 34.35465 MiB
echo human_filesize(filesize('file.zip'), 5);
?>
Upvotes: 0
Reputation: 32953
With good old printf :
printf("%.2f MB",filesize("../uploads/" . $dirArray[$index]) * .000000953674316);
Maybe, because it's a bit clearer what the intention is:
printf("%.2f MB",filesize("../uploads/" . $dirArray[$index]) / (1024 * 1024));
Upvotes: 3
Reputation: 33163
number_format()
is good, and don't forget that round()
can round the number to any precision you want.
Upvotes: 1
Reputation: 146390
You can format numbers with the number_format() function.
Edit: the manual page contains a user comment you may like: http://es.php.net/manual/en/function.number-format.php#72969
Upvotes: 6