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

In this post I am going to share Simple Javascript function 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 other readable format, So that user can easily judge the actual size of files. Like if you have provided some files for downloading you can also display the size of files in user friendly manner by using following function.


Here is the javascript function convert file size from bytes to KB, MB, GB and so on..

function converFromBytes(bytes,decimalLength) {
   if(bytes == 0) return '0 Bytes';
   var k = 1000,
       dm = decimalLength || 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 point length see following example.

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

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


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.