打赏

js比较数字相等

示例代码:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>js比较数字相等</title>
    </head>

    <body>

        <script type="text/javascript">
            //设置误差范围值--机器精度(对于js来说是2^-52)
            //ES6定义了Number.EPSILON,之前未定义Number.EPSILON
            if(!Number.EPSILON) {
                Number.EPSILON = Math.pow(2, -52)
            }

            function numberCloseEnoughToEqual(a, b) {
                return(a - b) < Number.EPSILON;
            }
            console.log(numberCloseEnoughToEqual((0.1 + 0.2), 0.3)); //true
        </script>
    </body>

</html>

 

posted @ 2018-01-16 16:10  孟繁贵  阅读(5275)  评论(0编辑  收藏  举报
TOP