Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to convert bytes to KB or MB or GB or TB or PB or EB or ZB or YB in JavaScript

1 Answer

0 votes
function convert_file_size(bytes, decimals = 2) {
   	if (bytes === 0) return '0 Bytes';
   
    const unit = 1024;
    const dec = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(unit));

    return parseFloat((bytes / Math.pow(unit, i)).toFixed(dec)) + ' ' + sizes[i];
}
  
  
console.log(convert_file_size(63521));
console.log(convert_file_size(37913521));
console.log(convert_file_size(3789913521));
console.log(convert_file_size(3723789913521));
console.log(convert_file_size(3399829987913521));
console.log(convert_file_size(9853399998791352198));
console.log(convert_file_size(9853399998424791352198));
console.log(convert_file_size(100985339999842450791352198));
  
    
    
/*
run:
    
"62.03 KB"
"36.16 MB"
"3.53 GB"
"3.39 TB"
"3.02 PB"
"8.55 EB"
"8.35 ZB"
"83.53 YB"
       
*/

 



answered Nov 5, 2021 by avibootz
...