标签:span tar 返回 结果 cti star 原型 blog temp
var a = 2.255; var b = a.toFixed(2); console.log(b);
以上代码,按预期正常四舍五入得到结果应该是2.26,但实际返回值为2.25
js浮点数精度作为前端必踩坑,谁也逃不过,不过我们可以改写原型上的方法达到目的
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; } var a = 2.255; var b = a.toFixed(2); console.log(b); 返回2.26
标签:span tar 返回 结果 cti star 原型 blog temp
原文地址:http://www.cnblogs.com/hcxy/p/7652855.html