JS实现Byte单位的字节 转成KB,MB,GB

function change(limit){
    var size = "";
    if(limit < 0.1 * 1024){                            //小于0.1KB,则转化成B
        size = limit.toFixed(2) + "B"
    }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB,则转化成KB
        size = (limit/1024).toFixed(2) + "KB"
    }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB,则转化成MB
        size = (limit/(1024 * 1024)).toFixed(2) + "MB"
    }else{                                            //其他转化成GB
        size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
    }

    var sizeStr = size + "";                        //转成字符串
    var index = sizeStr.indexOf(".");                    //获取小数点处的索引
    var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
    if(dou == "00"){                                //判断后两位是否为00,如果是则删除00                
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
    }
    return size;
}

var newLimit = change(1048576);
console.log(newLimit);

本文由站长原创或收集,不代表本站立场,如若转载,请注明出处:http://www.swzhinan.com/post/228.html

本文 暂无 评论

回复给

欢迎点评

联系我们

站长QQ:384827360

站长邮件:384827360@qq.com

工作时间:周一至周五,9:30-15:30,节假日休息

QR code