如何实现parseFloat四舍五入保留小数点后2位

1:

t.toFixed(2);

2:

t=Math.round(t*100)/100; 
alert(t);

3:

<script> a=3.4534134; alert(parseInt(a*100)/100) </script>

 

补充:

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

例如,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 2018-11-21 14:51  马元昊  阅读(1794)  评论(0编辑  收藏  举报