所以我创建了这个函数,它将字节数调整为正确的二进制单位。我遇到的问题是,每当文件在 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
,或 1000
到 1024
之间的任何数字,在您的情况下,有 4 位有效数字,但您告诉代码给出 3。因此,1.01e+3
.
如果要将数字四舍五入到小数点后 3 位,请考虑改为Math.round(size*1000)/1000
。