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 }));Report a problem with this exampleOpens a pre-filled issue on GitHub.