开发者

Limiting Number of Digits in PHP

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("../uplo开发者_Python百科ads/" . $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.


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


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));


number_format() is good, and don't forget that round() can round the number to any precision you want.


Here is simple nice function: Quick PHP


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);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜