1 function change(limit){ 2 var size = ""; 3 if(limit < 0.1 * 1024){ //小于0.1KB,则转化成B 4 size = limit.toFixed(2) + "B" 5 }else if(limit < 0.1 * 1024 * 1024){ //小于0.1MB,则转化成KB 6 size = (limit/1024).toFixed(2) + "KB" 7 }else if(limit < 0.1 * 1024 * 1024 * 1024){ //小于0.1GB,则转化成MB 8 size = (limit/(1024 * 1024)).toFixed(2) + "MB" 9 }else{ //其他转化成GB 10 size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB" 11 } 12 13 var sizeStr = size + ""; //转成字符串 14 var index = sizeStr.indexOf("."); //获取小数点处的索引 15 var dou = sizeStr.substr(index + 1 ,2) //获取小数点后两位的值 16 if(dou == "00"){ //判断后两位是否为00,如果是则删除00 17 return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2) 18 } 19 return size; 20 } 21 22 var newLimit = change(1048576); 23 console.log(newLimit);