关于四舍五入的问题,toFixed()

来源:互联网 发布:企业淘宝费用预算 编辑:程序博客网 时间:2024/05/03 22:42
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
关于四舍五入问题,在2000可以,在98会报错.
那是因为toFixed (Jscript 5.5)才支持,98是ie5.0,JavaScript 的版本是(JScript5.0)版本.所以就会提示:"对象不支持此属性或方法!".
为了版本兼容,我们得自己写函数实现.

<script>
// by wanghr100
/* 这样,就可以直接用toFixed()了.*/
Number.prototype.toFixed=function(len)
{
    var add = 0;
    var s,temp;
    var s1 = this + "";
    var start = s1.indexOf(".");
    if(s1.substr(start+len+1,1)>=5)add=1;
    var temp = Math.pow(10,len);
    s = Math.floor(this * temp) + add;
    return s/temp;
}
alert((52.277).toFixed(2))
alert((100.024).toFixed(1))
</script>

//应该还有更好的算法,大家试试看吧:)<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击