Skip to content

Instantly share code, notes, and snippets.

@zentala
Created September 27, 2017 11:57
Show Gist options
  • Save zentala/1e6f72438796d74531803cc3833c039c to your computer and use it in GitHub Desktop.
Save zentala/1e6f72438796d74531803cc3833c039c to your computer and use it in GitHub Desktop.
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

WOW NICE!!!!

@no-1imit
Copy link

Clever

@justsanjit
Copy link

Thank you for sharing!

@jerrygreen
Copy link

Absolutely cool snippet

@bqrichards
Copy link

Thank you! Helped a lot.

@nonorval
Copy link

Awesome snippet. Thanks!

@PujitU
Copy link

PujitU commented Jan 17, 2022

This helped a lot! Thank you

@Mtillmann
Copy link

Nice concept. I've forked it to support IEC units as well

@Zelow79
Copy link

Zelow79 commented Feb 1, 2023

Very nice, gonna use myself. Thanks, I did make some minor changes though.

export function formatBytes(bytes, dm = 2) {
  if (bytes == 0) return '0 Bytes';
  var k = 1024,
    sizes = [`${bytes <= 1 ? "Byte" : "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];
}```

@bavani69
Copy link

Awesome!

@SebiBasti
Copy link

Perfect! Exactly what I was looking for. 👍

@kwhitaker
Copy link

Great work, and thanks!

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