Convert the file size expressed in bytes to the appropriate unit

WBOY
Release: 2016-07-25 09:10:49
Original
932 people have browsed it
I saw someone shared code similar to this. Share a piece of code that supports arbitrarily large numbers and is quite simple.
  1. function formatFileSize($fileSize)
  2. {
  3. $unit = array(' Bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB');
  4. $i = 0;
  5. /*
  6. while($fileSize >= 1024 && $i < 8)
  7. {
  8. $fileSize /= 1024;
  9. ++$i;
  10. }
  11. * /
  12. /*
  13. The above code can also be optimized
  14. Since computers do multiplication faster than division
  15. */
  16. $inv = 1 / 1024;
  17. while($fileSize >= 1024 && $i < 8)
  18. {
  19. $fileSize *= $inv;
  20. ++$i;
  21. }
  22. //return sprintf("%.2f", $fileSize) . $unit[$i];
  23. // Correct the previous result to Integer, but the output is a floating point number with two meaningless 0 decimal places
  24. $fileSizeTmp = sprintf("%.2f", $fileSize);
  25. // The result of the following code will be correct in 99.99% of cases, Unless you use "super large numbers". :)
  26. return ($fileSizeTmp - (int)$fileSizeTmp ? $fileSizeTmp : $fileSize) . $unit[$i];
  27. }
Copy code
  1. //Test code
  2. echo formatFileSize(43453765345); // Result: 40.47 GB
  3. echo formatFileSize(4345376534545643543633655244525); // Result: 3594411.22 YB
  4. echo formatFileSize(2048); // Result: 2 KB
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template