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

toFixed 不能四舍五入问题

时间:2018-04-19 17:44:52      阅读:412      评论:0      收藏:0      [点我收藏+]

标签:处理   number   ++   prot   pre   ret   直接   0.00   千分位   

最近在项目中遇见一个bug,数据在移动端与pc端不一致,金额少了0.01,原因是js在处理0.005的时候直接舍去了千分位,直接上解决方法

 

Number.prototype.toFixed = function(s) {  
       var changenum = (parseInt(this * Math.pow(10, s) + 0.5) /         
       Math.pow(10, s)).toString();  
            index = changenum.indexOf(".");  
            if (index < 0 && s > 0) {  
                changenum = changenum + "."; 
                for (i = 0; i < s; i++) {  
                    changenum = changenum + "0";  
                }  
  
            } else {  
                index = changenum.length - index;  
                for (i = 0; i < (s - index) + 1; i++) {  
                    changenum = changenum + "0";  
                }  
  
        }  
  
        return changenum;  
  }    

  

toFixed 不能四舍五入问题

标签:处理   number   ++   prot   pre   ret   直接   0.00   千分位   

原文地址:https://www.cnblogs.com/zhubei/p/8884524.html

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