Skip to content

Instantly share code, notes, and snippets.

@Mtillmann
Forked from zentala/formatBytes.js
Last active December 31, 2022 10:22
Show Gist options
  • Save Mtillmann/09eb937df543c04f9df7d1ff038e2272 to your computer and use it in GitHub Desktop.
Save Mtillmann/09eb937df543c04f9df7d1ff038e2272 to your computer and use it in GitHub Desktop.
Convert size in bytes to human readable format (JavaScript)
export function formatBytes(bytes, decimals = 2, format = 'KB') {
if (bytes < 1) {
return '0 B';
}
const k = format === 'kB' ? 1000 : 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
const sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
const suffix = [format === 'kB' ? sizes[i].toLowerCase() : sizes[i], 'B'];
if (format === 'KiB') {
suffix.splice(1, 0, 'i');
}
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + suffix.join('');
}
// Usage:
// formatBytes(bytes,decimals, format)
// format can either be 'KiB', 'KB' or 'kB'. If you use 'kB', 1000 will be used to calculate size
formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment