当前位置:网站首页>教你一文解决 js 数字精度丢失问题
教你一文解决 js 数字精度丢失问题
2022-07-28 23:56:00 【韩旭在努力】
一、关于为什么要解决精度丢失
可以看下例子,因为js失去精度问题也是常见的问题,正常我们可以四舍五入或者 toFixed保留小数这种去解决
现在遇到问题是我们明知道计算结果是等于0.01的但是最后的结果确实true,如果我们遇到运算问题,小数数值比对问题,那么我们就必须要去解决他,否则也就会出现上者情况,出现逻辑判断出错问题
二、怎么解决js的计算精度丢失问题?
正常来说如果是 小数点保留后2位、3位等等,我们可以使用常见的 * 百位数、千位数 实现整位结果后 将结果在除以对应的数位实现结果,如下
console.log(5.22 - 5.21);
console.log((5.22 * 100 - 5.21 * 100) / 100);
根据上方的描述我们再去着眼看我们最开始的例子
结果也就成了我们想要的结果
三、toPrecision 特定方法返回四舍五入长度字符串
当然toFixed也是可以实现对应的长度取舍效果的,因为各大浏览器针对toFixed的各类结果都是不同的有兴趣的同学可以参考下下面这篇文章
toFixed详解
在这里我们只介绍 toPrecision 参照方法详解
那么我们也就知道了此方法是用来干什么的
当然再有一点也就是从左到右 不为0的位置开始计算
上方举例 我们的结果是0.01
如果我们去使用toPrecision的话,那么要填写的参数则为1
返还的结果也就是我们想要的 0.01
然后我们搭配 parseFloat 对字符串进行一个浮点数值转换后,然后对比得出最后结果
console.log(5.22 - 5.21 < 0.01);
console.log((5.22 * 100 - 5.21 * 100) / 100 < 0.01);
var num = 5.22 - 5.21;
console.log(parseFloat(num.toPrecision(1)) < 0.01);
结语
每天创作一点点
开心快乐一整天
点赞关注加收藏
美好一天又一天
铁铁们 感谢支持 我需要你们的三连
边栏推荐
- Wechat campus bathroom reservation applet graduation design finished product (5) assignment
- Wechat campus bathroom reservation of small program completion work (6) opening defense ppt
- Wechat campus bathroom reservation for the finished product of applet graduation design (7) mid term inspection report
- In the second round, 1000 okaleido tiger were sold out in one hour after logging in to binance NFT again
- Deep learning | matlab implementation of TCN time convolution neural network spatialdropoutlayer parameter description
- (完美解决)为什么在train/val/test数据集上用train模式效果都很好,但是在eval模式下全部很差
- Charles -- teach you how to use the packet capturing tool from 0-1
- 图扑软件亮相 2022 福州数博会,携手共创数字新时代
- ACM SIGIR 2022 | 美团技术团队精选论文解读
- [Commons lang3 topic] 004- numberutils topic
猜你喜欢
Hilbert 变换与瞬时频率
Day2:三种语言暴刷牛客130题
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(7)中期检查报告
如何执行建设项目的时间影响分析?
Techo hub Fuzhou Station dry goods attack | talk with developers about new industrial intelligence technology
Consumer unit 消费单元
SystemVerilog-连接和复制运算符
B- 树 ~
How to carry out engineering implementation of DDD Domain Driven Design
如何在WordPress中创建一个自定义404错误页面
随机推荐
Station B "crashed" from beginning to end 2021.07.13 we collapsed like this (Reprint)
QT静态编译程序(Mingw编译)
Mathematical modeling and detailed explanation of basic knowledge (common knowledge points of Chemistry)
Interview shock 69: is TCP reliable? Why?
Selenium wire obtains Baidu Index
🧐 Table1 | finish your third line watch in one second
[target detection] Introduction to yolor theory + practical test visdrone data set
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(5)任务书
SQL Server 只有数据库文件,没有日志文件,恢复数据时报1813错误的解决方案
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(7)中期检查报告
一元函数积分学之1__不定积分
Connect with Alipay payment
What opportunities does the London gold real-time market bring?
返回*this的成员函数
iNFTnews | 元宇宙购物体验将成为吸引消费者的一大利器
图扑软件亮相 2022 福州数博会,携手共创数字新时代
[Commons lang3 topic] 003- randomstringutils topic
NFT 项目的 7 种市场营销策略
新拟态个人引导页源码
追踪伦敦银实时行情的方法有哪些?