First write a demo to reproduce the problem. I am using a js online testing environment [Open]
Rewrite the displaynum() function
function displaynum(){var num = 22.77;alert(num + 10);}Clicking the Show button results show 32.7699999999996 N decimals appear.
Not all numbers will have this phenomenon, except for 22.99 2.777, it seems that these numbers are not special.
I checked some information. One is the bug in JS floating point calculation, and the other is related to the final conversion of the computer to binary calculation. However, why not all decimals have this phenomenon? I don’t know at the moment. I will go deeper if I have time.
There are two solutions now. The first is to use the JS .toFixed(n) method to directly obtain n-digit decimals. I personally think this method will have some problems in data accuracy. If the data accuracy requirements are not high, you can use it. The second method is to write your own js operation method.
The following is a custom addition function. Adding this method will avoid the above problems.
function addNum(num1,num2){var sq1,sq2,m;try{sq1=num1.toString().split(".")[1].length;} catch(e){sq1=0;}try{sq2=num2.toString().split(".")[1].length;} catch(e){sq2=0;}m=Math.pow(10,Math.max(sq1,sq2));return ( num1 * m + num2 * m ) / m;}Of course, it can also be written as alert((num * 3+10 * 3) /3); this way, there will be no more decimals in n.
alert((num * 3+10 * 3) /3); and alert(num+10); are different from alert(num+10); these two ways of writing computers to convert to binary operations at the bottom layer. Perhaps this is the reason for the above problems.
The above article on the js decimal calculating the decimal point and displaying multiple decimals is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.