JavaScript 将字节转换为可读字符串
给定文件的大小(以字节为单位),任务是使用JavaScript将其转换为可读形式。以下是一些讨论的方法。
示例1: 此示例将文件大小(以字节为单位)转换为可读形式。它以十进制方式显示值,并对于小于1024字节的值仍保持在字节单位。
let size = function (bytes) {
if (bytes === 0) {
return "0.00 B";
}
let e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, e)).toFixed(2) +
' ' + ' KMGTP'.charAt(e) + 'B';
}
let bytes = 2007777777770;
console.log(bytes + " bytes = " + size(bytes));
输出
2007777777770 bytes = 1.83 TB
示例2: 该示例将文件大小(以字节为单位)转换为人类可读格式。它以十进制形式显示值,对于小于1024字节的情况,保持以字节为单位。但采用一种不同的方法。
function getSize(size) {
let sizes = [' Bytes', ' KB', ' MB', ' GB',
' TB', ' PB', ' EB', ' ZB', ' YB'];
for (let i = 1; i < sizes.length; i++) {
if (size < Math.pow(1024, i))
return (Math.round((size / Math.pow(
1024, i - 1)) * 100) / 100) + sizes[i - 1];
}
return size;
}
let bytes = 1024;
console.log(bytes + " bytes = " + getSize(bytes));
输出
1024 bytes = 1 KB