Posted By

kendsnyder on 01/18/11


Tagged

String convert


Versions (?)

Convert bytes to text


 / Published in: PHP
 

URL: bytes-to-text

  1. function bytesToText($bytes, $precision = 2, $units = null) {
  2. static $suffix = array('b', 'KB', 'MB', 'GB', 'TB');
  3. if ($units) {
  4. $power = array_search($units, $suffix);
  5. $i = $power;
  6. while ($i-- > 0) {
  7. $bytes /= 1024;
  8. }
  9.  
  10. } else {
  11. $bytes = (float) $bytes;
  12. $power = 0;
  13. while ($bytes >= 1000) {
  14. $bytes /= 1024;
  15. $power++;
  16. }
  17. }
  18. if ($power == 0) {
  19. $precision = 0;
  20. }
  21. return number_format($bytes, $precision) . $suffix[$power];
  22. }

Report this snippet  

You need to login to post a comment.