javascript 字节在 1000 到 1024 之间的文件大小函数故障

javascript filesize function glitch with bytes between 1000 and 1024

所以我创建了这个函数,它使字节数适应正确的二进制单位。我遇到的问题是,只要文件在 1000 到 1024 字节之间,它就会显示为:1.02e+3 KB。我是做错了什么还是忘记捕捉所有异常?感谢您的帮助。

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];

function grid_filesizeCellClientTemplate(bytes) {
    if (!bytes)
        return "";

    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    var size = (bytes / Math.pow(1024, Math.floor(e)));
    var unit = ce_sizeSuffixes[e];
    //bug with a size >= 1000 and < 1024
    return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';
}

解决方案:

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];
function grid_filesizeCellClientTemplate(bytes) {
if (!bytes)
    return "";

var e = Math.floor(Math.log(bytes) / Math.log(1024));
var size = (bytes / Math.round(size * 1000) / 1000));
var unit = ce_sizeSuffixes[e];
//bug with a size >= 1000 and < 1024
return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';

toPrecision 输出格式化为给定有效数字位数的数字。 1010,或在您的情况下 10001024 之间的任何数字,有 4 个有效数字,但您告诉代码给出 3。因此,1.01e+3.

如果您想将数字四舍五入到小数点后 3 位,请考虑 Math.round(size*1000)/1000