JS数据容量单位转换

2019/08/29 · 干货 · 741次阅读
// 数据容量单位转换
var bytesToSize = (function() {
    var base = 1024,
        baseLog = Math.log(base),
        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    return function(bytes, precision) {
        if (bytes === 0) return '0B';
        var i = parseInt(Math.floor(Math.log(bytes) / baseLog), 10);
        return (bytes / Math.pow(base, i)).toFixed(precision || 0) + sizes[i];
    };
}());

使用方法

bytesToSize(1024, 2); //1.00KB

bytesToSize(10485760); //10MB

bytesToSize(1099511627776); //1TB

喝杯水

标签:JS数据容量单位转换

最后编辑于:2019/08/29 02:57

添加新评论

  1. 2019-09-11 17:34
    就这么简单?
    回复