How to convert file size in bytes to KB, MB, GB, TB and PB in Javascript

1 Answer

0 votes
function convert_file_size(bytes, decimals = 2) {
   if (bytes === 0) return '0 Bytes';
    
   var decimals = decimals < 0 ? 0 : decimals;
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
   var n = Math.floor(Math.log(bytes) / Math.log(1024));
    
   return parseFloat((bytes / Math.pow(1024, n)).toFixed(decimals)) + ' ' + sizes[n];
}
 
 
document.write(convert_file_size(200) + "<br />");
document.write(convert_file_size(1000) + "<br />");
document.write(convert_file_size(1024) + "<br />");
document.write(convert_file_size(1234) + "<br />");
document.write(convert_file_size(1234, 3) + "<br />");
document.write(convert_file_size(63521) + "<br />");
document.write(convert_file_size(7913521) + "<br />");
document.write(convert_file_size(87913521, 3) + "<br />");
document.write(convert_file_size(9987913521) + "<br />");
document.write(convert_file_size(3999987913521) + "<br />");
document.write(convert_file_size(98533999987913521) + "<br />");
 
   
/*
run:
   
200 Bytes
1000 Bytes
1 KB
1.21 KB
1.205 KB
62.03 KB
7.55 MB
83.841 MB
9.3 GB
3.64 TB
87.52 PB
      
*/

 



answered Sep 18, 2019 by avibootz
edited Sep 18, 2019 by avibootz
...