将文件大小以字节为单位转换为人类可读的字符串 [英] Converting file size in bytes to human-readable string

查看:197
本文介绍了将文件大小以字节为单位转换为人类可读的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此函数将文件大小(以字节为单位)转换为人类可读的文件大小:

I'm using this function to convert a file size in bytes to a human-readable file size:

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

但是,这似乎不是100%准确。例如:

However, it seems like this isn't 100% accurate. For example:

getReadableFileSizeString(1551859712); // output is "1.4 GB"

这不应该是1.5 GB?似乎1024的划分正在失去精度。我完全误解了某些东西,或者有更好的方法吗?

Shouldn't this be "1.5 GB"? It seems like the division by 1024 is losing precision. Am I totally misunderstanding something or is there a better way to do this?

推荐答案

这取决于你是否想要使用二进制文件或者十进制约定。

It depends on whether you want to use the binary or decimal convention.

RAM,例如,总是用二进制来衡量,所以要表达1551859712,因为~1.4GiB是正确的。

RAM, for instance, is always measured in binary, so to express 1551859712 as ~1.4GiB would be correct.

另一方面,硬盘制造商喜欢使用小数,因此他们会称之为~1.6GB。

On the other hand, hard disk manufacturers like to use decimal, so they would call it ~1.6GB.

只是令人困惑,软盘使用两个系统的混合 - 它们的1MB实际上是1024000字节。

And just to be confusing, floppy disks use a mixture of the two systems - their 1MB is actually 1024000 bytes.

这篇关于将文件大小以字节为单位转换为人类可读的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆