当前位置:网站首页>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 了。
边栏推荐
- What are MySQL locks and classifications
- 通达OA 首页门户工作台
- Gbase 8C system table PG_ conversion
- 去除网页滚动条方法以及内外边距
- Return a tree structure data
- Swift开发学习
- Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
- 【 tutoriel】 Chrome ferme les cors et les messages de la politique inter - domaines et apporte des cookies à travers les domaines
- 5. File operation
- MySQL学习03
猜你喜欢

Redis: simple use of redis

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

What are MySQL locks and classifications

Deep learning notes (constantly updating...)

Servlet中数据传到JSP页面使用el表达式${}无法显示问题

Depth (penetration) selector:: v-deep/deep/ and > > >
![[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)](/img/f1/b17631639cb4f0f58007b86476bcc2.gif)
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)

8 free, HD, copyright free video material download websites are recommended

4. 类和对象

内存池(内核角度理解new开辟空间的过程)
随机推荐
Awk from getting started to getting into the ground (3) the built-in functions printf and print of awk realize formatted printing
The sandbox explains its vision for the meta universe platform
What are MySQL locks and classifications
My creation anniversary
Pytorch convolution network regularization dropblock
使用Go语言实现try{}catch{}finally
COM and cn
GBase 8c系统表-pg_class
How do browsers render pages?
Kotlin middle process understanding and Practice (I)
RestCloud ETL 跨库数据聚合运算
可視化yolov5格式數據集(labelme json文件)
The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
Thread safe singleton mode
stm32F407-------IIC通讯协议
y54.第三章 Kubernetes从入门到精通 -- ingress(二七)
502 (bad gateway) causes and Solutions
GBase 8c触发器(三)
深度学习笔记(持续更新中。。。)
easyExcel