需求:字节单位换算的场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function byteConvert(bytes) { if (isNaN(bytes)) { return ''; } let symbols = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; let exp = Math.floor(Math.log(bytes) / Math.log(2)); if (exp < 1) { exp = 0; } let i = Math.floor(exp / 10); bytes = bytes / Math.pow(2, 10 * i);
if (bytes.toString().length > bytes.toFixed(2).toString().length) { bytes = bytes.toFixed(2); } return bytes + ' ' + symbols[i]; };
// 函数调用 console.log(byteConvert(109784));//107.21 KB
|
详解:https://juejin.cn/post/6844904018238504967