Converts a number in bytes to a human-readable string.
Number.prototype.toPrecision()
to truncate the number to a certain number of digits.precision
, to use a default precision of 3
digits.addSpace
, to add space between the number and unit by default.const prettyBytes = (num, precision = 3, addSpace = true) => {
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
const exponent = Math.min(
Math.floor(Math.log10(num < 0 ? -num : num) / 3),
UNITS.length - 1
);
const n = Number(
((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)
);
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
};
prettyBytes(1000); // '1 KB'
prettyBytes(-27145424323.5821, 5); // '-27.145 GB'
prettyBytes(123456789, 3, false); // '123MB'
JavaScript, String
Converts a color code to an rgb()
or rgba()
string if alpha value is provided.
JavaScript, String
Converts the values of RGB components to a hexadecimal color code.
JavaScript, String
Formats a number using the local number format order.