我通过PHP将此代码转换为秘密大小(以字节为单位)。
现在,我想使用JavaScript将这些尺寸转换为人类可读的尺寸。我想将此代码转换为JavaScript,如下所示:
function formatSizeUnits(bytes){
if (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
else if (bytes >= 1048576) { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
else if (bytes >= 1024) { bytes = (bytes / 1024).toFixed(2) + " KB"; }
else if (bytes > 1) { bytes = bytes + " bytes"; }
else if (bytes == 1) { bytes = bytes + " byte"; }
else { bytes = "0 bytes"; }
return bytes;
}
这是正确的方法吗?有没有更简单的方法?
从此:(来源)
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
注意:这是原始代码,请在下面使用固定版本。Aliceljm不再激活她复制的代码
现在,未缩小固定版本,并且ES6版本:(按社区)
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
现在,固定版本:( 由Stackoverflow的社区提供,+由JSCompress缩小)
function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}
用法 :
// formatBytes(bytes,decimals)
formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB
演示/来源:
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// ** Demo code **
var p = document.querySelector('p'),
input = document.querySelector('input');
function setText(v){
p.innerHTML = formatBytes(v);
}
// bind 'input' event
input.addEventListener('input', function(){
setText( this.value )
})
// set initial text
setText(input.value);
<input type="text" value="1000">
<p></p>
PS:更改k = 1000
或sizes = ["..."]
根据需要(位或字节)
(1)为什么字节= 0是“ n / a”?不只是“ 0 B”吗?(2)Math.round没有精度参数。我最好用
(bytes / Math.pow(1024, i)).toPrecision(3)
toFixed(n)
toPrecision(n)
对于所有值都具有一致的精度可能更合适。为了避免尾随零(例如:),bytesToSize(1000) // return "1.00 KB"
我们可以使用parseFloat(x)
。我建议将最后一行替换为:return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
。与以往的变化的结果是:bytesToSize(1000) // return "1 KB"
/bytesToSize(1100) // return "1.1 KB"
/bytesToSize(1110) // return "1.11 KB
/bytesToSize(1111) // also return "1.11 KB"
我相信复数形式用于0:“ 0字节”
我想说minify很好,但是在stackexchange答案中,最好具有更详细且可读的代码。
KB = SI单位的开尔文字节。这是荒谬的。应该是kB。