JavaScript 字节单位换算函数【详解】
前言:我们在日常开发中,经常会遇到字节单位换算的场景。一般用简单的除法来计算时,都会遇到计算精度的问题。下面,我们着重要将的是一种精确字节单位换算的详解: 1. 先看代码 const byteConvert = function(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 b...