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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

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

1 Answer

0 votes
function convert_file_size(bytes: number, decimals: number = 2) : string {
   if (bytes === 0) return '0 Bytes';
   
   const unit: number = 1024;
   const dec: number = decimals < 0 ? 0 : decimals;
   const sizes: string[] = ['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

Related questions

...