当前位置:网站首页>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 了。
边栏推荐
- 基于线程池的生产者消费者模型(含阻塞队列)
- Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
- GBase 8c系统表-pg_class
- My creation anniversary
- Trial setup and use of idea GoLand development tool
- Groovy, "try with resources" construction alternative
- Visual yolov5 format data set (labelme JSON file)
- GBase 8c系统表-pg_authid
- 4. 类和对象
- QT qcombobox add qccheckbox (drop-down list box insert check box, including source code + comments)
猜你喜欢

How do it students find short-term internships? Which is better, short-term internship or long-term internship?

微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題

可視化yolov5格式數據集(labelme json文件)

Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)

Detailed analysis of micro service component sentinel (hystrix)

Create + register sub apps_ Define routes, global routes and sub routes

y54.第三章 Kubernetes从入门到精通 -- ingress(二七)

Solution for processing overtime orders (Overtime unpaid)

What are MySQL locks and classifications

基于线程池的生产者消费者模型(含阻塞队列)
随机推荐
【CodeForces】CF1338A - Powered Addition【二进制】
COM and cn
Trial setup and use of idea GoLand development tool
GBase 8c系统表-pg_collation
The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}
《上市风云》荐书——唯勇气最可贵
人脸识别6- face_recognition_py-基于OpenCV使用Haar级联与dlib库进行人脸检测及实时跟踪
GBase 8c触发器(三)
es6 filter() 数组过滤方法总结
The Sandbox阐释对元宇宙平台的愿景
Detailed analysis of micro service component sentinel (hystrix)
[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
stm32F407-------IIC通讯协议
My creation anniversary
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
机器学习笔记(持续更新中。。。)
【教程】chrome关闭跨域策略cors、samesite,跨域带上cookie
Apple releases MacOS 11.6.4 update: mainly security fixes
Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks