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,884 questions

51,810 answers

573 users

How to convert bytes to KB or MB or GB or TB or PB or EB or ZB or YB in Node.js

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(63221));
console.log(convert_file_size(37915521));
console.log(convert_file_size(3789917521));
console.log(convert_file_size(3723789915521));
console.log(convert_file_size(3399829987813521));
console.log(convert_file_size(9853399598791352198));
console.log(convert_file_size(9853399498424791352198));
console.log(convert_file_size(100985339939842450791352198));
   
   
     
     
/*
run:
     
61.74 KB
36.16 MB
3.53 GB
3.39 TB
3.02 PB
8.55 EB
8.35 ZB
83.53 YB
        
*/

 



answered Jan 31, 2022 by avibootz

Related questions

...