js 将文件的大小转换成 B KB MB GB的方法教程

  • 内容
  • 相关

以前写过一篇关于在php中将一个文件的大小(以字节为单位),转化成以合适的单位(B,KB,MB,GB)来表示的教程教程,由于博主个人习惯把一些不重要的逻辑放到用户的浏览器中去执行,也就是用JS来处理。所以就写了一个利用 js 来将文件大小转化为B KB MB GB为单位的转化方法。

例1:js 字节转换成 B KB MB GB 的方法

js函数代码:

<script>
function sizeTostr(size) {
    var data = "";
    if (size < 0.1 * 1024) { //如果小于0.1KB转化成B  
        data = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB  
        data = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB  
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB  
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    var sizestr = data + "";
    var len = sizestr.indexOf("\.");
    var dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {//当小数点后为00时 去掉小数部分  
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
}  
</script>

函数调用方法:

<script>
console.log(sizeTostr(1000));
console.log(sizeTostr(102400));
console.log(sizeTostr(10240000));
console.log(sizeTostr(1000111111));
</script>

输出结果:

0.98KB
100KB
9.77MB
0.93GB

例2:js实现KB、MB、GB、TB单位转换

看了上面中例1的代码,是不是感觉很简单,只是一些数据的比较,那么接下来看一下例2的代码。

js函数代码:

<script>
// c 参数:表示要被转化的容量大小,以字节为单
// b 参数:表示如果转换时出小数,四舍五入保留多少位 默认为2位小数
function formatBytes(a, b) { 
    if (0 == a) return "0 B"; 
    var c = 1024, d = b || 2, e = ["B", "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];
}
</script>

函数的调用:

<script>
console.log(formatBytes(1234));
console.log(formatBytes(1234, 3)); 
console.log(formatBytes(123400, 3)); 
console.log(formatBytes(12340000, 3)); 
console.log(formatBytes(12340000000, 3)); 
console.log(formatBytes(12340000000000, 3)); 
console.log(formatBytes(1234000000000000, 3)); 
</script>

输出值:

1.21 KB
1.205 KB
120.508 KB
11.768 MB
11.493 GB
11.223 TB
1.096 PB
黑蜘蛛

本文标签:

版权声明:若无特殊注明,本文皆为《ღ軍尐ღ》原创,转载请保留文章出处。

字数统计:本文共有 《1611》 个。

本文链接:js 将文件的大小转换成 B KB MB GB的方法教程 - https://4dn.net/jsxx/114.html