function getSizeInKMG(num) { if(isNaN(num)) { alert(num + "不是一个数字!"); return false; } num = parseInt(num); var unit = [" B", " KB", " MB", " GB"]; for(var i = 0; i < unit.length; i += 1) { if(num < 1024) { num = num + ""; if(num.indexOf(".") != -1 && num.indexOf(".") != 3) { num = num.substring(0,4); } else { num = num.substring(0,3); } break; } else { num = num/1024; } } //num = (num+"").replace(/(\d*\.\d{0,2})\d*/ig, "$1"); return num + unit[i]; } document.writeln(getSizeInKMG(10254784));
做在线存储时的一段代码,用来将一个数字转换成最合适的单位形式,比如10254784会转换成9.77MB.