0
0
GGGiovanny Gongora
Converts a number in bytes to a human-readable string.
const prettyBytes = (num: number, precision: number = 3, addSpace: boolean = true) => {
const UNITS: Array<string> = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
const exponent: number = Math.min(
Math.floor(Math.log10(num < 0 ? -num : num) / 3),
UNITS.length - 1
);
const n: number = Number(
((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)
);
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
};