JS解决加减乘除浮点类型丢失精度问题
当我们在前端使用js来执行运算时,会有丢失精度的问题。
例如:
console.log("使用js原生态方法");
console.log(" 1.01 + 1.02 ="+(1.01 + 1.02));
console.log(" 1.01 - 1.02 ="+(1.01 - 1.02));
console.log(" 0.000001 / 0.0001 ="+(0.000001 / 0.0001));
console.log(" 0.012345 * 0.000001 ="+(0.012345 * 0.000001));
???
-----------------------------------
输出结果:
使用js原生态方法
1.01 + 1.02 =2.0300000000000002
1.01 - 1.02 =-0.010000000000000009
0.000001 / 0.0001 =0.009999999999999998
0.012345 * 0.000001 =1.2344999999999999e-8
解决方法:
<script type="text/javascript">
??? // 两个浮点数求和
??? function accAdd(num1,num2){
?????? var r1,r2,m;
?????? try{
?????????? r1 = num1.toString().split(‘.‘)[1].length;
?????? }catch(e){
?????????? r1 = 0;
?????? }
?????? try{
?????????? r2=num2.toString().split(".")[1].length;
?????? }catch(e){
?????????? r2=0;
?????? }
?????? m=Math.pow(10,Math.max(r1,r2));
?????? // return (num1*m+num2*m)/m;
?????? return Math.round(num1*m+num2*m)/m;
??? }
?? ?
??? // 两个浮点数相减
??? function accSub(num1,num2){
?????? var r1,r2,m;
?????? try{
?????????? r1 = num1.toString().split(‘.‘)[1].length;
?????? }catch(e){
?????????? r1 = 0;
?????? }
?????? try{
?????????? r2=num2.toString().split(".")[1].length;
?????? }catch(e){
?????????? r2=0;
?????? }
?????? m=Math.pow(10,Math.max(r1,r2));
?????? n=(r1>=r2)?r1:r2;
?????? return (Math.round(num1*m-num2*m)/m).toFixed(n);
??? }
??? // 两个浮点数相除
??? function accDiv(num1,num2){
?????? var t1,t2,r1,r2;
?????? try{
?????????? t1 = num1.toString().split(‘.‘)[1].length;
?????? }catch(e){
?????????? t1 = 0;
?????? }
?????? try{
?????????? t2=num2.toString().split(".")[1].length;
?????? }catch(e){
?????????? t2=0;
?????? }
?????? r1=Number(num1.toString().replace(".",""));
?????? r2=Number(num2.toString().replace(".",""));
?????? return (r1/r2)*Math.pow(10,t2-t1);
??? }
?? ?
// 两个浮点数相乘
??? function accMul(num1,num2){
?????? var m=0,s1=num1.toString(),s2=num2.toString();
??? try{m+=s1.split(".")[1].length}catch(e){};
??? try{m+=s2.split(".")[1].length}catch(e){};
??? return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
??? }
?? ?
? </script>
?
? <script>
console.log("使用js原生态方法");
??? console.log(" 1.01 + 1.02 ="+(1.01 + 1.02));
??? console.log(" 1.01 - 1.02 ="+(1.01 - 1.02));
??? console.log(" 0.000001 / 0.0001 ="+(0.000001 / 0.0001));
??? console.log(" 0.012345 * 0.000001 ="+(0.012345 * 0.000001));
??? console.log("-----------------");
??? console.log("使用自定义方法");
??? console.log(" 1.01 + 1.02 ="+accAdd(1.01,1.02));
??? console.log(" 1.01 - 1.02 ="+accSub(1.01,1.02));
??? console.log(" 0.000001 / 0.0001 ="+accDiv(0.000001,0.0001));
??? console.log(" 0.012345 * 0.000001 ="+accMul(0.012345,0.000001));
? </script>
------------------
输出结果
使用js原生态方法
1.01 + 1.02 =2.0300000000000002
1.01 - 1.02 =-0.010000000000000009
0.000001 / 0.0001 =0.009999999999999998
0.012345 * 0.000001 =1.2344999999999999e-8
-----------------
使用自定义方法:
1.01 + 1.02 =2.03
1.01 - 1.02 =-0.01
0.000001 / 0.0001 =0.01
0.012345 * 0.000001 =1.2345e-8