我使用这个函数将文件大小(以字节为单位)转换为人类可读的文件大小:
零二线函数
var i = -1;
var byteUnits =[英国‘计划生育’‘兆’,‘和合’,‘PB’‘EB”、“ZB’,‘YB];
do {
fileSizeInBytes /= 1024;
我+;
while (fileSizeInBytes > 1024)
数学归来。max(fileSizeInBytes, 0.1)。toFixed(1) + byteUnits[i];
的
控制台日志(getReadableFileSizeString (1551859712);//输出是“1.4 GB”
然而,这似乎不是百分之百准确的。例如:
getReadableFileSizeString(1551859712); // output is "1.4 GB"
不应该是“1.5 GB”吗?除以1024似乎失去了精度。是我完全误解了什么,还是有更好的办法?
@Andrew V的typescript版本带有新的“模板文字类型”
export const humanFileSize = (bytes: number): `${number} ${'B' | 'KB' | 'MB' | 'GB' | 'TB'}` => {
const index = Math.floor(Math.log(bytes) / Math.log(1024));
return `${Number((bytes / Math.pow(1024, index)).toFixed(2)) * 1} ${(['B', 'KB', 'MB', 'GB', 'TB'] as const)[index]}`;
};
这是我的-也适用于真正大的文件-_-
function formatFileSize(size)
{
var sizes = [' Bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
for (var 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;
}