Code Snippets
/

Format Bytes as a Human String

Format Bytes as a Human String

Showing `1457280 bytes` is hostile UX; showing `1.39 MB` (or `1.46 MB` if you use SI) is what users expect. This snippet covers the binary IEC variant (KiB, MiB, GiB), the decimal SI variant (KB, MB, GB), and a configurable helper that picks the unit, precision, and separator. Use it for upload progress, storage dashboards, or anywhere a raw byte count would otherwise leak into the UI.

JavaScript
Easy
3 snippets
math
utility
code-template

399 views

6

function formatBytesBinary(bytes, decimals = 2) {
    if (bytes === 0) return '0 B';
    const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
    const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024));
    const idx = Math.min(i, units.length - 1);
    const value = bytes / Math.pow(1024, idx);
    return `${value.toFixed(decimals)} ${units[idx]}`;
}

console.log(formatBytesBinary(0));       // 0 B
console.log(formatBytesBinary(1024));    // 1.00 KiB
console.log(formatBytesBinary(1048576)); // 1.00 MiB
console.log(formatBytesBinary(1500000)); // 1.43 MiB

Picking the right unit reduces to dividing by 1024 until the value is small, which Math.log(bytes) / Math.log(1024) does in a single step. Flooring the log gives the unit index; clamping with Math.min prevents overflow past the largest unit you have a label for. IEC units (KiB, MiB) are technically correct for binary multiples and are increasingly common in developer tools (Linux du -h, GitHub release sizes). Use Math.abs(bytes) so negative values (rare, but seen in delta accounting) format the same way.