Skip to content

Instantly share code, notes, and snippets.

@behomonth
Forked from zentala/formatBytes.js
Created February 23, 2023 17:44
Show Gist options
  • Save behomonth/e0a67a88b32d5d4c40b571ccec7f99ae to your computer and use it in GitHub Desktop.
Save behomonth/e0a67a88b32d5d4c40b571ccec7f99ae 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
@behomonth
Copy link
Author

Convert size in bytes to human readable format JS

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