当前位置:网站首页>javeScript 0.1 + 0.2 == 0.3的问题
javeScript 0.1 + 0.2 == 0.3的问题
2022-07-03 02:19:00 【weixin_49035434】
根据双精度浮点数的定义,Number类型中有效的整数范围是-0x1fffffffffffff至0x1fffffffffffff,所以Number无法精确表示此范围外的整数。
同样根据浮点数的定义,非整数的Number类型无法用 ==(===也不行) 来比较,一段著名的代码,这也正是我们第三题的问题,为什么在JavaScript中,0.1+0.2不能=0.3:
console.log( 0.1 + 0.2 == 0.3);
这里输出的结果是false,说明两边不相等的,这是浮点运算的特点,也是很多同学疑惑的来源,浮点数运算的精度问题导致等式左右的结果并不是严格相等,而是相差了个微小的值。
所以实际上,这里错误的不是结论,而是比较的方法,正确的比较方法是使用JavaScript提供的最小精度值:
console.log( Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON);
检查等式左右两边差的绝对值是否小于最小精度,才是正确的比较浮点数的方法。这段代码结果就是 true 了。
边栏推荐
- easyExcel
- Leetcode (540) -- a single element in an ordered array
- 人脸识别6- face_recognition_py-基于OpenCV使用Haar级联与dlib库进行人脸检测及实时跟踪
- 使用Go语言实现try{}catch{}finally
- Groovy, "try with resources" construction alternative
- stm32F407-------ADC
- [shutter] pull the navigation bar sideways (drawer component | pageview component)
- 单词单词单词
- Socket编程
- Thread safe singleton mode
猜你喜欢
Deep learning notes (constantly updating...)
通达OA 首页门户工作台
Recommendation letter of "listing situation" -- courage is the most valuable
PyTorch 卷积网络正则化 DropBlock
Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
[shutter] pull the navigation bar sideways (drawer component | pageview component)
机器学习笔记(持续更新中。。。)
udp接收队列以及多次初始化的测试
Producer consumer model based on thread pool (including blocking queue)
Coroutinecontext in kotlin
随机推荐
es6 filter() 数组过滤方法总结
GBase 8c系统表-pg_am
Kotlin middle process understanding and Practice (II)
微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
GBase 8c系统表-pg_auth_members
CFdiv2-Fixed Point Guessing-(区间答案二分)
stm32F407-------ADC
Tongda OA homepage portal workbench
内存池(内核角度理解new开辟空间的过程)
Groovy, "try with resources" construction alternative
Cfdiv2 Fixed Point Guessing - (2 points for Interval answer)
require.context
Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
Socket programming
GBase 8c系统表pg_database
Socket编程
MySQL学习03
awk从入门到入土(1)awk初次会面
Kotlin middle process understanding and Practice (I)