Home>

Regarding the addition, subtraction, multiplication, and division of javascript decimals, there are multiple decimals.I researched it myself,And made relevant tests,Gain a lot of knowledge points,

Share an interesting test with you:

0.1 + 0.2 == 0.3 //false

Suddenly depressed,Ok! The original 0.1 + 0.2 becomes:0.30000000000000004

Another 2.4/0.8 =>2.9999999999999996 There is no way to change this,Both are converted to integers (2.4 * 100)/(0.8 * 100)

10.22 Now I need to subtract 0.11 and the result value appears a lot of decimals 10.110000000000001, then I used the tofixed method to filter the decimals,But I don't know which kind of efficiency is the same as the previous conversion to integer.it is good! Let's try it again!

var date1=new date ();
for (var i=0;i<10000;i ++) {
 var result1=(10.22-0.11) .tofixed (2);
}
alert (new date ()-date1);//Inefficient
var date2=new date ();
for (var j=0;j<10000;j ++) {
 var result2=(10.22 * 1000-0.11 * 1000)/1000;
}
alert (new date ()-date2);//High efficiency
alert (0.1 + 0.2 == 0.3);//Since returning false
alert (0.1 + 0.2);//Since 0.30000000000000004 is returned
alert (parsefloat (0.1) + parsefloat (0.2));//still returns 0.30000000000000004

Checked some information,One is a bug in javascript floating-point calculation, and the other is related to the computer's final conversion to binary calculation.But why not all decimals have this phenomenon,I don't know at the moment,Have time to go deeper.

Solution:

There are two ways to solve this problem,The first is to use javascript's tofixed (n) method to directly obtain n decimal places. However, I think this method will have some problems in data accuracy.Can be used if the data accuracy is not high.

alert ((0.1 + 0.2) .tofixed (1));

The second method is to write the calculation method yourself.Here are the custom addition functions,Adding in this way avoids the above problems.

//Custom addition
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;
}
alert (addnum (0.1, 0.2));

Of course, a simpler can also be written:alert ((num * 3 + 10 * 3)/3);This will not appear n decimal places.

alert ((num * 3 + 10 * 3)/3);and alert (num + 10);There are differences between the two forms of computer's underlying conversion into binary operations.Maybe this is the reason for the above problem,It remains to be studied in depth,We can discuss more.

  • Previous Php get regular expression for hyperlink text content (five methods)
  • Next Method for customizing android shutdown interface of android source code exploration