Simple Javascript function to convert file size from bytes to KB, MB, GB, TB, PB, EB, ZB, YB

Information like, Javascript, URL Parameters

In this membership I am going to share Simple Javascript discharge faithfulness to convert file size from bytes to KB, MB, GB, TB, PB, EB, ZB, YB. By default size of files in bytes format, you can make it more human readable by converting bytes to appendage readable format, So that adherent can easily scrutinize the actual size of files. Like if you have provided some files for downloading you can moreover display the size of files in enthusiast animate look by using taking into account acquit yourself.

Here is the javascript deed convert file size from bytes to KB, MB, GB and consequently on the subject of..

function converFromBytes(bytes,decimalLength) {
   if(bytes == 0) return '0 Bytes';
   var k = 1000,
       dm = decimalPoint || 2,
       sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
       i = Math.floor(Math.log(bytes) / Math.log(k));
   return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

Where

bytes:-

Provide file size in bytes format and it is mandatory parameter.

decimalLength:-

It is optional parameter choose the decimal narrowing length see once example.

converFromBytes(5000);       // 5 KB
converFromBytes(5123);       // 5.12 KB
converFromBytes(5123, 3);    // 5.123 KB

Add above pretense in you custom javascript library and use any where you habit onvert file size from bytes to KB, MB, GB, just call converFromBytes() and pass file size in bytes.

Leave a Reply