码迷,mamicode.com
首页 > 其他好文 > 详细

toFixed内置四舍五入错误

时间:2017-10-11 21:45:42      阅读:123      评论:0      收藏:0      [点我收藏+]

标签: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

 

toFixed内置四舍五入错误

标签:span   tar   返回   结果   cti   star   原型   blog   temp   

原文地址:http://www.cnblogs.com/hcxy/p/7652855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!