当前位置:网站首页>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 了。
边栏推荐
- stm32F407-------DMA
- Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
- Prohibited package name
- stm32F407-------IIC通讯协议
- Qt之QComboBox添加QCheckBox(下拉列表框插入复选框,含源码+注释)
- Depth (penetration) selector:: v-deep/deep/ and > > >
- Tongda OA homepage portal workbench
- stm32F407-------ADC
- Leetcode(540)——有序数组中的单一元素
- The Sandbox阐释对元宇宙平台的愿景
猜你喜欢

Deep learning notes (constantly updating...)

Job object of collaboration in kotlin

4. Classes and objects

Coroutinecontext in kotlin

Ni visa fails after LabVIEW installs the third-party visa software

PyTorch 卷积网络正则化 DropBlock

easyExcel

Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现

Distributed transaction solution

awk从入门到入土(0)awk概述
随机推荐
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)
easyPOI
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
Gbase 8C system table PG_ conversion
Groovy, "try with resources" construction alternative
Tongda OA homepage portal workbench
Return a tree structure data
stm32F407-------DMA
去除网页滚动条方法以及内外边距
基于线程池的生产者消费者模型(含阻塞队列)
Su Shimin: 25 principles of work and life
我的创作纪念日
Startup mode and scope builder of collaboration in kotlin
CFdiv2-Fixed Point Guessing-(区间答案二分)
Awk from getting started to getting into the ground (3) the built-in functions printf and print of awk realize formatted printing
leetcode961. Find the elements repeated N times in the array with length 2n
What are the key points often asked in the redis interview
Producer consumer model based on thread pool (including blocking queue)