当前位置:网站首页>JS数字精度丢失的原因及解决方案
JS数字精度丢失的原因及解决方案
2022-07-27 23:50:00 【清风细雨_林木木】
大纲
1.了解原因
2.解决方案
1.原因
因为在计算机中,数字先转二进制,然后运算,最后转十进制
例如:0.1 + 0.2
0.1 也就是0.0001100110011001100110011001100110011001100110011001101
0.2 也就是0.001100110011001100110011001100110011001100110011001101
即:
0.00011001100110011001100110011001100110011001100110011010 +
0.0011001100110011001100110011001100110011001100110011010 =
0.0100110011001100110011001100110011001100110011001100111
结果0.0100110011001100110011001100110011001100110011001100111再转换成十进制就是0.30000000000000004。
2.解决办法
(1)插件Decimal
0.1 + 0.2 // 0.30000000000000004
x = new Decimal(0.1)
y = x.plus(0.2) // '0.3'
(2)插件bignumber
x = new BigNumber(0.1)
y = x.plus(0.2)
(3)变成整数
function add(num1, num2) {
const num1Len = (num1.toString().split('.')[1] ).length;
const num2Len = (num2.toString().split('.')[1] ).length;
const maxLen = Math.pow(10, Math.max(num1Len, num2Len));
return (num1 * maxLen + num2 * maxLen) / maxLen;
}
边栏推荐
猜你喜欢

Storage practices for high-performance computing scenarios, see here

Docker builds MySQL master-slave locally

Sort out SQL performance optimization and collect classics!

HRD 1. 一个简单而靠谱的HRD的检测方法

idea常用的快捷键汇总

路由策略简介

股票问题5连

Cesium add dynamic pop-up

8000 word explanation of OBSA principle and application practice

Qlib教程——基于源码(二)本地数据保存与加载
随机推荐
我的富二代朋友
leetcode: 515. 在每个树行中找最大值
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
Dart code comments and documentation specification
Niuke multi School Game 3 A, c+ weight segment tree
Transplant QT system for i.mx6ull development board - cross compile QT code
“你“想当测试/开发程序员吗?努力发芽的我们......
8000 word explanation of OBSA principle and application practice
Software test interview question: what are the performance test indicators?
软件测试面试题:think_time的作用是什么?
【分布式开发】之 CAP 原则
Interview question 01.05. Primary editing
牛客多校第三场A,C+权值线段树
Leetcode 2351. the first letter that appears twice
Lambda表达式和Stream流
自定义事件
Lecture 16 of project practice: using the open close principle to realize the commodity price rule engine
登录功能实现
【样式集合1】tab 栏
Fluent call interface UI