个性化阅读
专注于IT技术分析

使用JavaScript将字节转换为人类可读的值(KB,MB,GB,TB,PB,EB,ZB,YB)

本文概述

在计算世界中, 千字节, 千兆字节等术语用于描述某些存储设备和系统内存中的空间。通常, 在Web应用程序中, 它们被显示给用户以描述他们在云中或需要以字节为单位进行测量的其他功能中有多少空间。显然, 如果你向他们显示字节数, 他们就不会知道文件/可用空间到底有多大, 相信我, 他们只会看到数字。

这就是为什么你需要使用已知的KB, MB, GB等度量符号以特定的符号显示此信息的原因。在JavaScript中, 这很容易通过本文今天将与你共享的2种方法来完成。两者(具有相同名称的方法)都希望将字节数作为整数或字符串作为第一个参数, 并返回带有用户可以读取的字符串的字符串。

A.基于1024字节的简短版本

基于1024的版本假定单个KB具有1024字节, 并且仅用3行代码, 你就可以轻松地将多个字节转换为可读的符号:

注意

从理论上讲, KB完全由1024组成, 因此该方法是两者中最准确的一种。

/**
 * Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
 * 
 * @param {Int} num The number of bytes.
 */
function readableBytes(bytes) {
    var i = Math.floor(Math.log(bytes) / Math.log(1024)), sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
}

该方法可以按以下方式使用:

// "1000 B"
readableBytes(1000);

// "9.42 MB"
readableBytes(9874321);

// "9.31 GB"
// The number of bytes as a string is accepted as well
readableBytes("10000000000");

// "648.37 TB"
readableBytes(712893712304234);

// "5.52 PB"
readableBytes(6212893712323224);

B.基于1000字节的版本

另一个选项将字节转换为可读格式, 但计数为1KB等于1000字节, 而不是第一个选项的1024。这增加了精度的余量, 但是可以与我们的第一种方法几乎相同的逻辑工作:

/**
 * Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
 * 
 * @param {Int} num The number of bytes.
 */
function readableBytes(num) {
    var neg = num < 0;

    var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    if (neg){
        num = -num;
    }

    if (num < 1){
        return (neg ? '-' : '') + num + ' B';
    }
    
    var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1);
    
    num = Number((num / Math.pow(1000, exponent)).toFixed(2));
    
    var unit = units[exponent];

    return (neg ? '-' : '') + num + ' ' + unit;
}

该方法可以按以下方式使用:

// "1 KB"
readableBytes(1000);

// "9.87 MB"
readableBytes(9874321);

// "10 GB"
// The number of bytes as a string is accepted as well
readableBytes("10000000000");

// "712.89 TB"
readableBytes(712893712304234);

// "6.21 PB"
readableBytes(6212893712323224);

编码愉快!

赞(0)
未经允许不得转载:srcmini » 使用JavaScript将字节转换为人类可读的值(KB,MB,GB,TB,PB,EB,ZB,YB)

评论 抢沙发

评论前必须登录!