Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vithalreddy/ba1d681990d7a837375cd9ee7c77c332 to your computer and use it in GitHub Desktop.
Save vithalreddy/ba1d681990d7a837375cd9ee7c77c332 to your computer and use it in GitHub Desktop.
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
@alvaaz
Copy link

alvaaz commented Mar 4, 2022

Thanks for this snippet :)

@NJ261
Copy link

NJ261 commented Aug 20, 2023

shouldn't the var k be 1024?

@cwollenhaupt
Copy link

You cannot pass 0 for decimalPoint, because 0 || 2 in JavaScript is 2. Instead you can declare decimalPoint with a default value:

function formatFileSize(bytes,decimalPoint = 2) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment