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>
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!