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

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 wanghr100 的 blog

关于四舍五入的问题,在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>

//应该还有更好的算法,大家试试看吧:)

本文关键:Number,toFixed,四舍五入,灰豆宝宝.net wanghr100
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top