Format bytes as KB, MB, GB
Convert a byte count into a short human-readable size such as 1.5 MB.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function formatBytes(bytes, decimals = 1) {
if (!Number.isFinite(bytes) || bytes < 0) throw new RangeError("bytes must be a non-negative number");
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
const value = bytes / 1024 ** i;
return `${Number(value.toFixed(decimals))} ${units[i]}`;
}Example / expected output
formatBytes(1536) // "1.5 KB"
formatBytes(5_000_000) // "4.8 MB"How it works
Uses base-1024 steps with the common KB/MB/GB labels. The number of decimals is configurable and trailing zeros are dropped. Negative or non-finite input throws instead of returning nonsense.
Related snippets
- JavaScript Tested
Format currency and numbers with Intl
Locale-aware money, percent and compact number formatting using the built-in Intl.NumberFormat.
- Python Tested
Format bytes as a human-readable size
Convert a byte count into KB, MB, GB and so on with a configurable number of decimals.
- PHP Tested
Format bytes as a readable size in PHP
Convert a number of bytes to KB, MB or GB with a chosen precision.
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.

