刘明野

JS数据容量单位转换

// 数据容量单位转换
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

本文为作者刘明野发布,未经允许禁止转载!
4239
1
0
发表留言

    就这么简单?

友情链接