在JavaScript中将大小(以字节为单位)转换为KB,MB,GB的正确方法 [英] Correct way to convert size in bytes to KB, MB, GB in JavaScript

查看:241
本文介绍了在JavaScript中将大小(以字节为单位)转换为KB,MB,GB的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过PHP获得了此代码来隐藏字节大小。

I got this code to covert size in bytes via PHP.

现在我想使用JavaScript将这些尺寸转换为人类可读尺寸。我试图将此代码转换为JavaScript,如下所示:

Now I want to convert those sizes to human readable sizes using JavaScript. I tried to convert this code to JavaScript, which looks like this:

function formatSizeUnits(bytes){
  if      (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
  else if (bytes >= 1048576)    { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
  else if (bytes >= 1024)       { bytes = (bytes / 1024).toFixed(2) + " KB"; }
  else if (bytes > 1)           { bytes = bytes + " bytes"; }
  else if (bytes == 1)          { bytes = bytes + " byte"; }
  else                          { bytes = "0 bytes"; }
  return bytes;
}

这是正确的方法吗?有更简单的方法吗?

Is this the correct way of doing this? Is there an easier way?

推荐答案

从这个:( 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];
};

注意:这是原始代码,请使用下面的固定版本。 Aliceljm 不再激活她复制的代码

Note : This is original code, Please use fixed version below. Aliceljm does not active her copied code anymore

现在,修正版: (由Stackoverflow社区提供,+由 JSCompress 缩小)

Now, Fixed version : (by Stackoverflow's community, + Minified by 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]}

用法:

// formatBytes(bytes,decimals)

formatBytes(1024);       // 1 KB
formatBytes('1024');     // 1 KB
formatBytes(1234);       // 1.21 KB
formatBytes(1234, 3);    // 1.205 KB

演示/来源:

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:根据需要更改 k = 1000 sizes = [...] 字节

PS : Change k = 1000 or sizes = ["..."] as you want (bits or bytes)

这篇关于在JavaScript中将大小(以字节为单位)转换为KB,MB,GB的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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