美文网首页
js toFixed如何做到"四舍五入"

js toFixed如何做到"四舍五入"

作者: G_whk | 来源:发表于2019-08-16 11:25 被阅读0次
    image

    如上图所示:

    JS的(2.55).toFixed(1)输出是2.5,而不是四舍五入的2.6,这是为什么呢???

    解决方法:

    if (!Number.prototype._toFixed) {
        Number.prototype._toFixed = Number.prototype.toFixed;
    }
    Number.prototype.toFixed = function(n) {
        return (this + 1e-14)._toFixed(n);
    };
    // 以上为兼容tofixed的代码。
    

    添加如上代码后即可做到以下效果。

    image

    相关文章

      网友评论

          本文标题:js toFixed如何做到"四舍五入"

          本文链接:https://www.haomeiwen.com/subject/zzdfsctx.html