This article mainly introduces PHP's method of converting Byte into KB, MB, GB, and TB. It analyzes the specific implementation method of PHP's conversion operation for Byte in the form of examples, involving PHP mathematical operations. For the use of the function, friends who need it can refer to
This article describes the method of converting the number of bytes into KB, MB, GB, and TB in PHP. Share it with everyone for your reference, the details are as follows:
The method of converting Byte into KB, MB, GB, and TB in Java was introduced earlier. Here, PHP is used to implement this function. The code is very simple:
<?php function getFilesize($num){ $p = 0; $format='bytes'; if($num>0 && $num<1024){ $p = 0; return number_format($num).' '.$format; } if($num>=1024 && $num<pow(1024, 2)){ $p = 1; $format = 'KB'; } if ($num>=pow(1024, 2) && $num<pow(1024, 3)) { $p = 2; $format = 'MB'; } if ($num>=pow(1024, 3) && $num<pow(1024, 4)) { $p = 3; $format = 'GB'; } if ($num>=pow(1024, 4) && $num<pow(1024, 5)) { $p = 3; $format = 'TB'; } $num /= pow(1024, $p); return number_format($num, 3).' '.$format; } echo "来自脚本之家www.jb51.net的测试结果:<br/>"; echo getFilesize(200)."<br/>"; echo getFilesize(20000)."<br/>"; echo getFilesize(2000000)."<br/>"; echo getFilesize(200000000)."<br/>"; echo getFilesize(20000000000)."<br/>"; echo getFilesize(2000000000000)."<br/>"; ?>
The running result is as follows:
The above is the detailed content of A brief introduction to PHP's method of converting bytes into KB, MB, GB, and TB. For more information, please follow other related articles on the PHP Chinese website!