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

不经意之间发现我一直在用的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

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值