Home  >  Article  >  Backend Development  >  PHP and JS implement a human-readable way to convert file size

PHP and JS implement a human-readable way to convert file size

WBOY
WBOYOriginal
2016-07-25 09:07:291123browse
  1. function my_formatSize($size){
  2. $size = doubleval($size);
  3. $rank =0;
  4. $rankchar ='Bytes';
  5. while($size>1024){
  6. $size = $size/1024;
  7. $rank++;
  8. }
  9. if($rank==1){
  10. $rankchar="KB";
  11. }
  12. else if($rank==2){
  13. $rankchar= "MB";
  14. }
  15. else if($rank==3){
  16. $rankchar="GB";
  17. }
  18. $size = number_format($size, 2, '.', '');
  19. return "" .$size." ".$rankchar;
  20. }
Copy code

2. js implementation code

  1. function my_formatSize($size){
  2. var size = parseFloat($size);
  3. var rank =0;
  4. var rankchar ='Bytes';
  5. while(size>1024){
  6. size = size/1024;
  7. rank++;
  8. }
  9. if(rank==1){
  10. rankchar="KB";
  11. }
  12. else if(rank==2){
  13. rankchar="MB";
  14. }
  15. else if(rank==3){
  16. rankchar="GB";
  17. }
  18. return size.toFixed(2)+ " "+ rankchar;
  19. }
  20. ?>
Copy code

Note: in the code Keep 2 decimal places.



Statement:
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