How to Convert File Size in Bytes to KB, MB, GB in Javascript

Generally, when we get the file size in JavaScript, it returns in bytes format. But if want, you can easily convert file size to human readable format using JavaScript. Our example code shows you how to convert file size in bytes to KB, MB, GB in Javascript.

For the better usability, the required code is grouped into the formatFileSize() function. The formatFileSize() function converts the size from bytes to KB, MB, GB, TB, PB, EB, ZB, YB using Javascript. The formatFileSize() function accepts the following parametters.

  • bytes – Required. Provide size in bytes format.
  • decimalPoint – Optional. Specify the decimal point.
function formatFileSize(bytes,decimalPoint) {
   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];

You only need to use the formatFileSize() function in JavaScript to convert file size units.

formatBytes(2000);       // 2 KB
formatBytes(2234);       // 2.23 KB
formatBytes(2234, 3);    // 2.234 KB

Leave a reply