这个方法是在一个例子中看到的,我测试了一下是小数点后四舍五入的功能

例如,5.05---->toFixed(1) 5.1

5.056-------->toFixed(2) 5.06

但是用到0.056时就出现问题了toFixed(1)的结果是0.0

有点奇怪的答案

下面的脚本是重写了toFixed(),这样0.056就可以转化到0.1了

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;
}

posted on 2008-06-23 16:18 湘江夜游神 阅读(6468) 评论(4)  编辑  收藏 所属分类: JavaScript

FeedBack:
# re: JS中的toFixed()方法
2008-11-02 15:46 | 搜索
????????????

a = 0.056;
b = a.toFixed(2);
document.write (b)

哪错了?很正常呀。
  回复  更多评论
  
# re: JS中的toFixed()方法
2009-01-07 23:27 | 1414嘛
a = 0.056;
b = a.toFixed(2);
document.write (b)

哪错了?很正常呀。
--------------------------
呵呵,是他写错了。你0.056.toFixed(1)就是结果0.0了,应该是0.1的。  回复  更多评论
  
# re: JS中的toFixed()方法
2009-01-08 11:45 | 湘江夜游神
@1414嘛
多谢指正,的确是我写错了,应该是toFixed(1)。已经改正  回复  更多评论
  
# re: JS中的toFixed()方法
2012-04-18 13:11 | eeee
eeeeee  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

Locations of visitors to this page