Blogger Information
Blog 175
fans 1
comment 0
visits 384809
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js中两个小数相减,出现的多位小数问题处理
dxp2tq的博客
Original
2924 people have browsed it

js中两个小数相减,出现的多位小数问题处理(扩展:加减乘除案例如下)

原理示例:

console.log(1-0.8);
变为 console.log((1 10 - 0.8 10) / 10);
即可得到正确的值

根据上述原理,可以封装一些方法出来解决此类问题。如下所示(Math.pow(x, y);表示求x的y次方):

//加

function floatAdd(arg1,arg2){

varr1,r2,m;

try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0}

try{r2=arg2.toString().split(“.”)[1].length}catch(e){r2=0}

  1. m=Math.pow(10,Math.max(r1,r2));

return(arg1m+arg2m)/m;

}

//减

function floatSub(arg1,arg2){

varr1,r2,m,n;

try{r1=arg1.toString().split(“.”)[1].length}catch(e){r1=0}

try{r2=arg2.toString().split(“.”)[1].length}catch(e){r2=0}

  1. m=Math.pow(10,Math.max(r1,r2));
  2. //动态控制精度长度
  3. n=(r1>=r2)?r1:r2;

return((arg1m-arg2m)/m).toFixed(n);

}

//乘

function floatMul(arg1,arg2) {

varm=0,s1=arg1.toString(),s2=arg2.toString();

try{m+=s1.split(“.”)[1].length}catch(e){}

try{m+=s2.split(“.”)[1].length}catch(e){}

returnNumber(s1.replace(“.”,””))*Number(s2.replace(“.”,””))/Math.pow(10,m);

}

//除

function floatDiv(arg1,arg2){

vart1=0,t2=0,r1,r2;

try{t1=arg1.toString().split(“.”)[1].length}catch(e){}

try{t2=arg2.toString().split(“.”)[1].length}catch(e){}

r1=Number(arg1.toString().replace(“.”,””));

r2=Number(arg2.toString().replace(“.”,””));

return(r1/r2)*Math.pow(10,t2-t1);

}

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post