A floating point error occurs during the multiplication of decimals in the (www.bkjia.com) Tutorial JS. You can test it as follows:
Reference content is as follows:
<Script>
Alert (11*22.9)
</Script> |
The result is 251.89999999999998 instead of 251.9.
This problem may be a headache for many people. How can this problem be solved? A solution is provided here. The general idea of solving the problem is to first enlarge the factor into an integer and then divide it by the corresponding multiples to get the correct result.
Reference content is as follows:
<Script defer>
Number. prototype. rate = function (){
Var oStr = this. toString ();
If (oStr. indexOf (".") =-1)
Return 1;
Else
Return Math. pow (10, parseInt (oStr. length-oStr.indexOf (".")-1 ));
}
Function tran (){
Args = tran. arguments;
Var temp = 1;
For (I = 0; I <args. length; I ++)
Temp * = args [I] * args [I]. rate ();
For (I = 0; I <args. length; I ++)
Temp/= args [I]. rate ();
Return temp
}
Alert (tran (11, 22.9 ));
</Script> |
This solution is troublesome, but it gives you a general idea about the actual process of solving this problem.