JS数值精度问题及toFixed()方法的解决方案

本文为转载内容(原文地址:JS中toFixed()方法的问题及解决方案

最近发现JS当中toFixed()方法存在一些问题,采用原生的Number对象的原型对象上的toFixed()方法时,规则并不是所谓的“四舍五入”或者是“四舍六入五成双”,所谓“四舍六入五成双”,在百度百科上给的解释是:也即“4舍6入5凑偶”这里“四”是指≤4 时舍去,"六"是指≥6时进上,"五"指的是根据5后面的数字来定,当5后有数时,舍5入1;当5后无有效数字时,需要分两种情况来讲:①5前为奇数,舍5入1;②5前为偶数,舍5不进。(0是最小的偶数) 。百度百科上涉及的几个例子在实际情况下确实成立,但不科学,并不能覆盖所有的情况。

测试浏览器:屌丝浏览器IE6以及高级屌丝浏览器IE78(此处为方便未使用原生IE678,不过IETester破天荒地表现良好,精确做法应该是一个版本对应一个虚拟机来测试)和所有现代主流浏览器包括IE9、IE10、FF、Chrome、Opera、Safari。(注:在使用IE10的类似firebug的开发工具时,采用兼容IE低版本浏览器模式时的测试结果跟使用原生低版本IE浏览器的测试结果不一致)

解决方案:重写 toFixed() 方法:

/**
 * [toFixed 重写四舍五入]
 * @param  {[type]} d [description]
 * @param  {[type]} n [description]
 * @return {[type]}   [description]
 */
function toFixed (d, n) {
    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 + "";
};

完整测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        /**
         * [toFixed 重写四舍五入]
         * @param  {[type]} d [description]
         * @param  {[type]} n [description]
         * @return {[type]}   [description]
         */
        function toFixed (d, n) {
            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 + "";
        };
    </script>
</head>
<body>
    <input type="button" value="显示0.009.toFixed(2)" onclick="alert(0.009.toFixed(2))"><br />
    <input type="button" value="显示0.123.toFixed(2)" onclick="alert(0.123.toFixed(2))"><br />
    <input type="button" value="显示0.125.toFixed(2)" onclick="alert(0.125.toFixed(2))"><br />
    <input type="button" value="显示0.126.toFixed(2)" onclick="alert(0.126.toFixed(2))"><br />
    <input type="button" value="显示20.445.toFixed(2)" onclick="alert(20.445.toFixed(2))"><br />
    <input onclick="alert(20.405.toFixed(2))" type="button" value="显示20.405.toFixed(2)"> <br />
    <input onclick="alert(20.415.toFixed(2))" type="button" value="显示20.415.toFixed(2)"> <br />
    <input onclick="alert(20.425.toFixed(2))" type="button" value="显示20.425.toFixed(2)"> <br />
    <input onclick="alert(20.435.toFixed(2))" type="button" value="显示20.435.toFixed(2)"> <br />
    <input onclick="alert(20.445.toFixed(2))" type="button" value="显示20.445.toFixed(2)"> <br />
    <input onclick="alert(20.455.toFixed(2))" type="button" value="显示20.455.toFixed(2)"> <br />
    <input onclick="alert(20.465.toFixed(2))" type="button" value="显示20.465.toFixed(2)"> <br />
    <input onclick="alert(20.475.toFixed(2))" type="button" value="显示20.475.toFixed(2)"> <br />
    <input onclick="alert(20.485.toFixed(2))" type="button" value="显示20.485.toFixed(2)"> <br />
    <input onclick="alert(20.495.toFixed(2))" type="button" value="显示20.495.toFixed(2)"> <br />
    <input onclick="alert(0.05.toFixed(1))" type="button" value="显示0.05.toFixed(1)"> <br />
    <input onclick="alert(0.15.toFixed(1))" type="button" value="显示0.15.toFixed(1)"> <br />
    <input onclick="alert(0.25.toFixed(1))" type="button" value="显示0.25.toFixed(1)"> <br />
    <input onclick="alert(0.35.toFixed(1))" type="button" value="显示0.35.toFixed(1)"> <br />
    <input onclick="alert(0.45.toFixed(1))" type="button" value="显示0.45.toFixed(1)"> <br />
    <input onclick="alert(0.55.toFixed(1))" type="button" value="显示0.55.toFixed(1)"> <br />
    <input onclick="alert(0.65.toFixed(1))" type="button" value="显示0.65.toFixed(1)"> <br />
    <input onclick="alert(0.75.toFixed(1))" type="button" value="显示0.75.toFixed(1)"> <br />
    <input onclick="alert(0.85.toFixed(1))" type="button" value="显示0.85.toFixed(1)"> <br />
    <input onclick="alert(0.95.toFixed(1))" type="button" value="显示0.95.toFixed(1)"> <br />
</body>
</html>

冯奎博客
请先登录后发表评论
  • latest comments
  • 总共0条评论