JavaScript Snippet

Format Bytes as a Human String

Difficulty: Easy

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.

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

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.