我希望能够获取一个文件,并且只以兆字节为单位显示它。例如,如果我有一个只有120kb或2mb的文件,我希望它分别以0.12mb和2mb的形式回显出来。
下面是我目前拥有的代码,希望有人能帮忙吗?
<?php
function byte_convert($size) {
# size smaller then 1kb
if ($size < 1024) return $size . ' Byte';
# size smaller then 1mb
if ($size < 1048576) return sprintf("%4.2f KB", $size/1024);
# size smaller then 1gb
if ($size < 1073741824) return sprintf("%4.2f MB", $size/1048576);
# size smaller then 1tb
if ($size < 1099511627776) return sprintf("%4.2f GB", $size/1073741824);
# size larger then 1tb
else return sprintf("%4.2f TB", $size/1073741824);
}
$file_path = "pic1.jpg";
$file_size = byte_convert(filesize($file_path));
echo $file_size;
?>
谢谢。
只需除以1024*1024
<?php
function get_mb($size) {
return sprintf("%4.2f MB", $size/1048576);
}
$file_path = "pic1.jpg";
$file_size = get_mb(filesize($file_path));
echo $file_size;
?>
function sizeFormat($bytes, $unit = "", $decimals = 2) {
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes)/log(1024));
$unit = array_search($pow, $units);
}
$value = ($bytes/pow(1024,floor($units[$unit])));
}
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
return sprintf('%.' . $decimals . 'f '.$unit, $value);
}
有了这个功能,你可以随心所欲:
sizeFormat('120', 'MB');
这里是伴侣:
<?php
function convert_to_mb($size)
{
$mb_size = $size / 1048576;
$format_size = number_format($mb_size, 2) . ' MB';
return $format_size;
}
?>