js格式化文件大小,将传入的字节,转成B、KB、MB、GB、TB等的两种方法:
方法一:
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); //当小数点后为00时 去掉小数部分 if (dec == "00") { return sizestr.substring(0, len) + sizestr.substr(len + 3, 2); } return sizestr; }
调用:
console.log(sizeTostr(1000)); console.log(sizeTostr(102400)); console.log(sizeTostr(10240000)); console.log(sizeTostr(1000111111));
输出:
0.98KB
100KB
9.77MB
0.93GB
方法二:
// 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]; }
调用:
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));
输出:
1.21 KB
1.205 KB
120.508 KB
11.768 MB
11.493 GB
11.223 TB
1.096 PB
方法二比方法一更加简便。