下面是一个将数字转换为符合新的国际标准的可读字符串的原型。
There are two ways to represent big numbers: You could either display
them in multiples of 1000 = 10 3 (base 10) or 1024 = 2 10 (base 2). If
you divide by 1000, you probably use the SI prefix names, if you
divide by 1024, you probably use the IEC prefix names. The problem
starts with dividing by 1024. Many applications use the SI prefix
names for it and some use the IEC prefix names. The current situation
is a mess. If you see SI prefix names you do not know whether the
number is divided by 1000 or 1024
https://wiki.ubuntu.com/UnitsPolicy
http://en.wikipedia.org/wiki/Template:Quantities_of_bytes
Object.defineProperty(Number.prototype,'fileSize',{value:function(a,b,c,d){
return (a=a?[1e3,'k','B']:[1024,'K','iB'],b=Math,c=b.log,
d=c(this)/c(a[0])|0,this/b.pow(a[0],d)).toFixed(2)
+' '+(d?(a[1]+'MGTPEZY')[--d]+a[2]:'Bytes');
},writable:false,enumerable:false});
这个函数不包含循环,所以它可能比其他一些函数快。
用法:
IEC前缀
console.log((186457865).fileSize()); // default IEC (power 1024)
//177.82 MiB
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB
如果prefix
console.log((186457865).fileSize(1)); //1,true for SI (power 1000)
//186.46 MB
//kB,MB,GB,TB,PB,EB,ZB,YB
我将IEC设置为默认值,因为我总是使用二进制模式来计算文件的大小…使用1024的幂
如果你只想在一个简短的线性函数中使用其中一个:
SI
function fileSizeSI(a,b,c,d,e){
return (b=Math,c=b.log,d=1e3,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
+' '+(e?'kMGTPEZY'[--e]+'B':'Bytes')
}
//kB,MB,GB,TB,PB,EB,ZB,YB
IEC
function fileSizeIEC(a,b,c,d,e){
return (b=Math,c=b.log,d=1024,e=c(a)/c(d)|0,a/b.pow(d,e)).toFixed(2)
+' '+(e?'KMGTPEZY'[--e]+'iB':'Bytes')
}
//KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB
用法:
console.log(fileSizeIEC(7412834521));
如果你有关于函数的问题尽管问