您的位置:首页 > Web前端 > JavaScript

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

2011-08-17 15:35 555 查看
日期:2007-12-25 作者:szsoho 来源:www.szsoho.com 点击: 1326 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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: