当前位置: 首页 > Web前端 > JavaScript

JavaScript精度丢失的原因及解决方法

时间:2023-03-26 20:50:22 JavaScript

浮点数精度丢失的原因因为计算机底层是用二进制实现的,所以有些数字是无法完整显示的。就像有些无理数不能完全显示,比如pi3.1415926...,0.3333...等。JavaScript遵循IEEE754规范,使用双精度存储(doubleprecision),占用64位。1位用来表示符号位,11位用来表示指数,52位用来表示尾数。因为在计算机底层,数值计算和运算都是用二进制来实现的,所以计算机没有办法准确表示浮点数,只能用近似相等的二进制数来表示浮点数的小数部分。数字精度丢失的一些典型场景//加法0.1+0.2=0.300000000000000040.7+0.1=0.7999999999999999//减法1.5-1.2=0.300000000000000040.3-0.2=0.09999999999999998//乘法1.1*100=110.000000000000010.8*3=2.4000000000000004//除法0.3/0.1=2.999999999999999960.69/10=0.068999999999999999Solutionthird-partylibrary:Decimal.jsbignnumber.jsbig.jshandwrittencode://additionfunctionplus(num1,num2){letr1,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}//subtractionfunctionsubtract(num1,num2){letr1,r2,m,n;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((num1*m-num2*m)/m).toFixed(n);}//乘法functionmultiply(num1,num2){letm=0,s1=num1.toString(),s2=num2.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)}//除法函数divide(num1,num2){让t1=0,t2=0,r1,r2;try{t1=num1.toString().split(".")[1].length}catch(e){}try{t2=num2.toString().split(".")[1].length}catch(e){}with(Math){r1=Number(num1.toString().replace(".",""))r2=Number(num2.toString().replace(".",""))returnmultiply((r1/r2),pow(10,t2-t1));//乘法配搭一起使用}}看了N篇关于precisionloss的文章,参考了很多其他博主的文章写的这篇文章