From this: ( source )
(从此:( 来源 ))
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];
}
Note : This is original code, Please use fixed version below.
(注意:这是原始代码,请在下面使用固定版本。)
Aliceljm does not active her copied code anymore(Aliceljm不再激活她复制的代码)
Now, Fixed version unminified, and ES6'ed: (by community)
(现在,未缩小固定版本,并且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];
}
Now, Fixed version : (by Stackoverflow's community, + Minified by JSCompress )
(现在,固定版本:( 由Stackoverflow的社区提供,+由JSCompress缩小 ))
function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]}
Usage :
(用法:)
// formatBytes(bytes,decimals)
formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB
Demo / source :
(演示/来源:)
function formatBytes(bytes,decimals) { if(bytes == 0) return '0 Bytes'; var k = 1024, dm = decimals <= 0 ? 0 : decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 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 : Change k = 1000
or sizes = ["..."]
as you want ( bits or bytes )
(PS:根据需要更改k = 1000
或sizes = ["..."]
( 位或字节 ))