【JS】toFixed不精准问题的解决办法 您所在的位置:网站首页 月干支的计算方法不准怎么办 【JS】toFixed不精准问题的解决办法

【JS】toFixed不精准问题的解决办法

2024-03-03 05:29| 来源: 网络整理| 查看: 265

不经意之间发现我一直在用的toFixed方法竟然有问题,我竟然糊涂的用它做了很多事!以下是我在chrome上的结果:

console.log(1.35.toFixed(1)); // 1.4 正确 console.log(1.335.toFixed(2));//1.33 错误 console.log(1.3335.toFixed(3));//1.33 错误 console.log(1.33335.toFixed(4));//1.3334 正确 console.log(1.333335.toFixed(5));//1.33333 错误 console.log(1.3333335.toFixed(6));//1.333333 错误

果然有问题,只能寻找解决办法了,那要怎么解决呢?

 

从网上找到的解决方法有下面两种(实际上还是一种方法):但是都未对负数进行处理

方法一:(定义一个全局方法,直接调用)

// num表示需要四舍五入的小数 // s表示需要保留几位小数 function toFixed(num, s) { var times = Math.pow(10, s); var des = parseInt((num * times + 0.5), 10) / times; return des; } console.log(toFixed(0.335, 2));//0.34 console.log(toFixed(-0.335, 2));//-0.34 console.log(toFixed(-1.5, 0));//-1 错误

方法二:重写toFixed方法:

Number.prototype.toFixed = function (s) { var times = Math.pow(10, s); var des = this * times + 0.5; des = parseInt(des, 10) / times; return des + ''; }; console.log(1.335.toFixed(2));//1.34 console.log((-1.5).toFixed(0));//-1 错误

 

当然如果仅仅是未对负数进行处理,我们还是可以改改代码的(用之前可以先判断正负数,如果是负数:先转为正数,处理了之后,再转成负数即可。。。。),但是(此时再感谢评论区的小伙伴给出的数据),我们用9.655保留两个小数,还是发现有问题!!!

console.log((9.655).toFixed(2));//9.65 错误

 

所以呀,又全网进行搜索,发现了下面这种方法,好用!!!

如果发现其它数据还是有问题,欢迎小伙伴们留言评论!!!

最终办法: // n表示需要四舍五入的小数 // d表示需要保留几位小数 function toFixed(n, d) { var s = n + ""; if (!d) d = 0; if (s.indexOf(".") == -1) s += "."; s += new Array(d + 1).join("0"); if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) { var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true; if (a == d + 2) { a = s.match(/\d/g); if (parseInt(a[a.length - 1]) > 4) { for (var i = a.length - 2; i >= 0; i--) { a[i] = parseInt(a[i]) + 1; if (a[i] == 10) { a[i] = 0; b = i != 1; } else break; } } s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2"); } if (b) s = s.substr(1); return (pm + s).replace(/\.$/, ""); } return this + ""; }; console.log(toFixed(0.335, 2));//0.34 console.log(toFixed(-0.335, 2));//-0.34 console.log(toFixed(-1.5, 0));//-2 正确 console.log(toFixed(-2999033.45645, 4));//-2999033.4565 console.log(toFixed(9.655, 2));//9.66

 

 

最下面的方法,原文链接:

https://blog.csdn.net/huangpb123/article/details/80530228

https://www.jianshu.com/p/cae048479372



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有