将字节数转换为可读的字符串。
根据存取字节数常用的单位构建一个数组字典。
使用 Number.toPrecision()
将数字截断为一定数量的数字。
将构建、美化好的字符串返回,并考虑提供的选项以及是否为负值。
省略第二个参数 precision
,使用默认精度为’3的数字。
addSpace`,默认情况下在数字和单位之间添加空格。
省略第三个参数
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(123456789); // 123 MB prettyBytes(-50); // -50 B prettyBytes(27145424323.5821); // 27.1 GB prettyBytes(27145424323.5821, 5); // 27.145 GB prettyBytes(5500, 3, false); // 5.5KB
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂