给定文件的大小(以字节为单位),如何使用JavaScript将其转换为人类可读的形式?下面本篇文章就来给大家介绍一下使用JavaScript将字节转换为人类可读字符串的方法,希望对大家有所帮助。
原文地址:
下面就通过示例来给大家介绍一下使用JavaScript将字节转换为人类可读的字符串的方法。
示例1:以十进制显示值,小于1024字节时,它以字节为单位
<script>
function size(bytes) {
if (bytes == 0) {
return "0.00 B";
}
var e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, e)).toFixed(2) +
' ' + ' KMGTP'.charAt(e) + 'B';
}
function Fun() {
var bytes = 2007777777770;
console.log(bytes+ " 字节 = "+ size(bytes) ) ;
}
Fun();
</script>
输出:
示例2:
<script>
function getSize(size) {
var sizes = [' Bytes', ' KB', ' MB', ' GB',
' TB', ' PB', ' EB', ' ZB', ' YB'];
for (var i = 1; i < sizes.length; i++) {
if (size < Math.pow(1024, i))
return (Math.round((size / Math.pow(
1024, i - 1)) * 100) / 100) + sizes[i - 1];
}
return size;
}
function Fun() {
var bytes = 2007;
console.log(bytes+ " 字节 = "+ getSize(bytes) ) ;
var bytes = 2377779;
console.log(bytes+ " 字节 = "+ getSize(bytes) ) ;
var bytes = 4566377779;
console.log(bytes+ " 字节 = "+ getSize(bytes) ) ;
}
Fun();
</script>
输出:
推荐阅读: