Format Byte Counts With IEC Units
Turn raw byte counts into readable IEC or SI strings with configurable decimals, spacing and correct handling of zero and negatives.
Code
const IEC_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
const SI_UNITS = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];
export function formatBytes(bytes, options = {}) {
if (typeof bytes !== "number" || !Number.isFinite(bytes)) {
throw new TypeError("bytes must be a finite number");
}
const { decimals = 1, base = 1024, space = true } = options;
if (base !== 1000 && base !== 1024) throw new RangeError("base must be 1000 or 1024");
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 6) {
throw new RangeError("decimals must be an integer between 0 and 6");
}
const units = base === 1024 ? IEC_UNITS : SI_UNITS;
const sign = bytes < 0 ? "-" : "";
let value = Math.abs(bytes);
let unitIndex = 0;
while (value >= base && unitIndex < units.length - 1) {
value /= base;
unitIndex += 1;
}
const fixed = value.toFixed(unitIndex === 0 ? 0 : decimals);
return `${sign}${fixed}${space ? " " : ""}${units[unitIndex]}`;
}
console.log(formatBytes(0));
console.log(formatBytes(1536));
console.log(formatBytes(1048576));
console.log(formatBytes(1500, { base: 1000, decimals: 2, space: false }));
console.log(formatBytes(-2048, { decimals: 0 }));Output
Captured from a sandboxed run of this snippet in the build pipeline.
0 B
1.5 KiB
1.0 MiB
1.50kB
-2 KiBInside the snippet
The code’s whole job belongs to the function formatBytes.
Iteration happens inside while (value >= base && unitIndex < units.length - 1) — everything outside it runs once. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.
What to watch for
- The guard
base !== 1000 && base !== 1024short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is export function formatBytes(bytes, options = {})
formatBytes is the public entry point; everything else in the file exists to support it.
Key statements
if (base !== 1000 && base !== 1024) throw new RangeError("base must be 1000 or 1024");
throw new RangeError("decimals must be an integer between 0 and 6");
return `${sign}${fixed}${space ? " " : ""}${units[unitIndex]}`;
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- What happens if the preconditions do not hold?
- Validation comes first — `TypeError` and `RangeError` marks the failure at `base !== 1000 && base !== 1024`, before any partial work happens.
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `formatBytes` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.