Home >Web Front-end >JS Tutorial >js implements precise calculation of arithmetic operations
An accurate calculation is crucial for a project, so how to achieve accurate calculation of arithmetic operations in js? The following article will share with you the precise calculation implemented by js.
JS cannot perform accurate calculation bug
When doing CRM, second-generation review requirements review details page. The numbers entered by the user need to be displayed in different places in proportion (the backend passes a decimal like 0.8).
A problem was found while doing dubheInvest = invest * (1 - ratio); operation. The details are as follows:
Sample code:
console.log( 1 - 0.8 ); //输出 0.19999999999999996 console.log( 6 * 0.7 ); //输出 4.199999999999999 console.log( 0.1 + 0.2 ); //输出 0.30000000000000004 console.log( 0.1 + 0.7 ); //输出 0.7999999999999999 console.log( 1.2 / 0.2 ); //输出 5.999999999999999
As you can see from the examples given above, the native js operation results are not necessarily accurate and will lose precision.
Solution
The principle of the solution is to multiply (expand) the floating point number by 10 to the nth power, convert the floating point number into an integer and then perform the corresponding operation, and finally get the result Divide (reduce) 10 to the nth power.
Principle example:
Change console.log(1-0.8); into console.log((1 * 10 - 0.8 * 10) / 10); to get the correct value
Based on the above principles, some methods can be encapsulated to solve such problems. As shown below (Math.pow(x, y); means finding the yth power of x):
//加法运算 function floatAdd(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; } //减法运算 function floatSub(arg1,arg2){ var r1,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} m=Math.pow(10,Math.max(r1,r2)); //动态控制精度长度 n=(r1>=r2)?r1:r2; return ((arg1*m-arg2*m)/m).toFixed(n); } //乘法运算 function floatMul(arg1,arg2) { 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); } //除法运算 function floatp(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){} r1=Number(arg1.toString().replace(".","")); r2=Number(arg2.toString().replace(".","")); return (r1/r2)*Math.pow(10,t2-t1); }
Related recommendations:
js accurate addition, subtraction, multiplication and division examples
The above is the detailed content of js implements precise calculation of arithmetic operations. For more information, please follow other related articles on the PHP Chinese website!