Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert size in bytes to human readable format (JavaScript)
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals || 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];
}
// Usage:
// formatBytes(bytes,decimals)
formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB
@tomek-m-coder
Copy link

tomek-m-coder commented Feb 2, 2020

WOW NICE!!!!

@no-1imit
Copy link

no-1imit commented Aug 12, 2020

Clever

@justsanjit
Copy link

justsanjit commented Sep 23, 2020

Thank you for sharing!

@jerrygreen
Copy link

jerrygreen commented Nov 27, 2020

Absolutely cool snippet

@bqrichards
Copy link

bqrichards commented Jun 21, 2021

Thank you! Helped a lot.

@nonorval
Copy link

nonorval commented Sep 28, 2021

Awesome snippet. Thanks!

@PujitU
Copy link

PujitU commented Jan 17, 2022

This helped a lot! Thank you

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