This article mainly introduces the precise calculation of JS floating-point number (add, subtract, multiply, divide) the need for friends can come to the reference, I hope to help you.
The code is as follows: <span style= "font-size:18px" >//Description: JavaScript addition results will be error, in two floating-point number added is more obvious. This function returns a more precise addition result. //Call: Accadd (ARG1,ARG2) //return value: Arg1 plus arg2 exact result function Accadd (arg1,arg2) { VAR r1,r2,m; try{r1=arg1.tostring (). Split (".") [1].length}catch (e) {r1=0} try{r2=arg2.tostring (). Split (".") [1].length}catch (e) {r2=0} M=math.pow (10,math.max (R1,R2)) return (arg1*m+arg2* m)/m }</span> code as follows: <span style= "font-size:18px" > //Description: JavaScript subtraction results will be incorrect Difference, the addition of two floating-point numbers will be more obvious. This function returns a more accurate subtraction result. //Call: Accsub (ARG1,ARG2) //return value: arg1 exact result of arg2 reduction function Accsub (arg1,arg2) { return Accadd (ARG1,-ARG2); }</span> Code is as follows: <span style= "font-size:18px" > //Description: JavaScript multiplication results will be error, It is more noticeable when multiplying two floating-point numbers. This function returns a more accurate result of the multiplication. //Call: Accmul (ARG1,ARG2) /return value: Arg1 times arg2 Exact result function Accmul (arg1,arg2) { & nbsp var m=0,s1=arg1.tostring (), s2=arg2.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) }</span> code is as follows: <span style= "font-size:18px" > //Description: JavaScript division results will be error , which is more obvious when dividing two floating-point numbers. This function returns a more precise division result. //Call: Accdiv (ARG1,ARG2) //return value: Arg1 divided by arg2 exact result function Accdiv (arg1,arg2) { VAR t1=0,t2=0,r1,r2; try{t1=arg1.tostring (). Split (".") [1].length}catch (e) {} try{t2=arg2.tostring (). Split (".") [1].length}catch (e) {} with (Math) { R1=number (arg1.tostring (). Replace (".", "")) R2=nUmber (Arg2.tostring (). Replace (".", "")) return (R1/R2) *pow (10,T2-T1); } }</span>