Update prettyBytes.md
This commit is contained in:
@ -4,20 +4,17 @@ Converts a number in bytes to a human-readable string.
|
|||||||
|
|
||||||
Use an array dictionary of units to be accessed based on the exponent.
|
Use an array dictionary of units to be accessed based on the exponent.
|
||||||
Use `Number.toPrecision()` to truncate the number to a certain number of digits.
|
Use `Number.toPrecision()` to truncate the number to a certain number of digits.
|
||||||
Return the prettified string by building it up, taking into account the supplied options and whether it is
|
Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not.
|
||||||
negative or not.
|
Omit the second argument, `precision`, to use a default precision of `3` digits.
|
||||||
|
Omit the third argument, `addSpace`, to add space between the number and unit by default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const prettyBytes = (num, precision = 3, addSpace = true) => {
|
const prettyBytes = (num, precision = 3, addSpace = true) => {
|
||||||
const UNITS = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
|
const UNITS = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
|
||||||
if (Math.abs(num) < 1) return num + ' B';
|
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 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));
|
const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
|
||||||
return (
|
return ((num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]);
|
||||||
(num < 0 ? '-' : '') +
|
|
||||||
n +
|
|
||||||
(addSpace ? ' ' : '') + UNITS[exponent]
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user