深圳soho网,small office home office
当前位置 : 深圳soho网 >>  web技术  >> 文章正文

js中如何保留两位小数(四舍五入)

日期:2007-12-25  作者:szsoho  来源:www.szsoho.com   点击:

function   cheng(num,n)  
{var   dd=1;  
var   tempnum;  
for(i=0;i<n;i++)  
{  
dd*=10;  
}  
tempnum=num*dd;  
tempnum=Math.round(tempnum);  
alert(tempnum/dd);  
}  
里面的两个参数:num:要转换的数据。n:转换的位数

------------------------------------------------------------------------------------------------------  

/*  
*     ForDight(Dight,How):数值格式化函数,Dight要  
*     格式化的   数字,How要保留的小数位数。  
*/  
function   ForDight(Dight,How)  
{  
            Dight   =   Math.round   (Dight*Math.pow(10,How))/Math.pow(10,How);  
            return   Dight;  
}  
alert(ForDight(12345.67890,2));  
</script>

-------------------------------------------------------------

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.30000000000000000001,2))