示例代码:

<!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>

 

相关文章:

  • 2021-10-16
  • 2021-10-16
  • 2022-12-23
  • 2021-08-07
  • 2022-01-02
  • 2021-07-11
  • 2021-10-27
猜你喜欢
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
  • 2021-07-08
  • 2021-06-15
  • 2022-12-23
  • 2021-05-19
相关资源
相似解决方案