格式化小数,并四舍五入

   //格式化小数,并四舍五入。如:formatNum(100.12345678,4)
   function formatNum(Num1,Num2)
   {
       if(isNaN(Num1)||isNaN(Num2))
       {
           return(0);
       }
       else
       {
           Num1=Num1.toString();
           Num2=parseInt(Num2);
           if(Num1.indexOf('.')==-1)
           {
               return(Num1);
           }
           else
           {
               var b=Num1.substring(0,Num1.indexOf('.')+Num2+1);
               var c=Num1.substring(Num1.indexOf('.')+Num2+1,Num1.indexOf('.')+Num2+2);
               if(c=="")
               {
                   return(b);
               }
               else if(parseInt(c)<5)
               {
                   return(b);
               }
               else
               {
                   return((Math.round(parseFloat(b)*Math.pow(10,Num2))+Math.round(parseFloat(Math.pow(0.1,Num2).toString().substring(0,Math.pow(0.1,Num2).toString().indexOf('.')+Num2+1))*Math.pow(10,Num2)))/Math.pow(10,Num2));
               }
               
           }
       }
  }
posted @ 2008-12-30 16:08    阅读(412)  评论(2编辑  收藏  举报