toFixed():numObj.toFixed([fractionDigits])

解决方案 »

  1.   

    toFixed方法要求浏览器的版本是5.5或更高
      

  2.   

    不限制版本和浏览器:<script language=JavaScript>
    function tofloat(f,dec) { 
    if(dec<0) return "Error:dec<0!"; 
    result=parseInt(f)+(dec==0?"":"."); 
    f-=parseInt(f); 
    if(f==0) 
    for(i=0;i<dec;i++) result+='0'; 
    else { 
    for(i=0;i<dec;i++) f*=10; 
    result+=parseInt(Math.round(f)); 

    return result; 

    alert(tofloat(11.20000000000000000001,5))
    </script>
      

  3.   

    <script language=JavaScript>
    function tofloat(f,dec) { 
    var ret,tmp;
    if(dec<0)return "Error:dec<0!"; 
    if(dec==0)return parseInt(f);
    with(Math){tmp=pow(10,dec);ret=round(f*tmp)/tmp;}
    try{tmp=String(ret).split(".")[1].length;}catch(e){tmp=0;ret+=".";}
    return ret+(new Array(dec-tmp+1).join("0")); 

    alert(tofloat(12.30000000000000000001,5))
    </script>