In the calculation of JS floating point value, many times there will be inaccurate situations, such as the following conditions
Console.log (2.2 + 2.1) // 4.300000000000001console.log (2.2-1.9) //0.30000000000000027console.log (2.2 * 2.2)//4.840000000000001console.log (2.1/0.3)//7.000000000000001console.log (10-9.99)//0.009999999999999787
Then on the Internet to find some solutions (refer to the bottom link of the blog post), the principle is to separate the floating point number from the dot to two integers, and then calculate. As follows:
Addition
function Add (A, b) {var c, D, e;try {c = a.tostring (). Split (".") [1].length;} catch (f) {c = 0;} try {d = b.tostring (). Split (".") [1].length;} catch (f) {d = 0;} return e = Math.pow (Math.max (c, D)), (Mul (A, E) + mul (b, E))/E;} Subtract function sub (a, b) {var c, D, e;try {c = a.tostring (). Split (".") [1].length;} catch (f) {c = 0;} try {d = b.tostring (). Split (".") [1].length;} catch (f) {d = 0;} return e = Math.pow (Math.max (c, D)), (Mul (A, E)-Mul (b, E))/E;} Division function Mul (A, b) {var c = 0,d = A.tostring (), E = b.tostring (); try {c + = D.split (".") [1].length;} catch (f) {}try {c + = E.split (".") [1].length;} catch (f) {}return number (D.replace (".", "")) * Number (E.replace (".", ""))/Math.pow (ten, c);} Multiply function Div (A, b) {var c, d, e = 0,f = 0;try {e = A.tostring (). Split (".") [1].length;} catch (g) {}try {f = b.tostring (). Split (".") [1].length;} catch (g) {}return c = number (a.tostring (). Replace (".", "")), d = number (b.tostring (). Replace (".", ""), Mul (C/D, Math.po W (Ten, F-e));}
This is a good way to do it. But when the project was just a place to use, for a place and paste such a piece of code, a little fuss about the feeling, then I temporarily used another method, the floating point is multiplied by 10 of the 10 to become an integer, calculated after the result is divided by 10 10. The results are as follows.
As can be seen, the method is still effective, is a bit of trouble. It is worth noting that in division there are two values multiplied by C, after which no need to be divided by C, I made this mistake, so I write it down.
Well, that's about it.
Reference Blog Link: http://blog.csdn.net/qinshenxue/article/details/43671763
Summary of calculation of JS floating-point number