这个函数可以对任意数字保留自定义小数位数,保留规则是包准的四舍五入,不足位数添0替补:
function round(num,digits){ if(isNaN(num)){ return "NaN"; } num = num.toString(); var dot = num.indexOf("."); if(dot==-1){ if(!digits){ return num; } var zero = ""; for(var i =0; i<digits;i++){ zero += "0"; } return (num+"."+zero); }else{ var integer = num.split(".")[0]; var decimals = num.split(".")[1]; var newDecimals; if(!digits){ return decimals.charAt(0)>=5?integer*1+1:integer; } if(decimals.length > digits){ var keyNum = decimals.charAt(digits-1); newDecimals = decimals.substr(0,digits-1)+(decimals.charAt(digits)>=5?keyNum*1+1:keyNum); return (integer+"."+newDecimals); }else{ var zero = ""; for(var i =0; i<digits-decimals.length;i++){ zero += "0"; } newDecimals = decimals+zero; return (integer+"."+newDecimals); } } } round(2.5485,2);//2.55 round(2.5485,3);//2.549 round(2.5485,6);//2.548500 round(2.5485,0);//3 round(2.5485);//3 round(2.4485);//2 round(2.4485,0);//2如果你不要末尾的0,直接将返回值乘以1:
round(2.5485,6)*1;//2.5485本文转载自:秋叶个人博客 http://www.mizuiren.com/482.html