This article describes how to accurately calculate addition and subtraction in js. For more information, see add and subtract. For example, 0.1 + 0.2 = 0.3 or 0.1-0.2 =-0.1
The Code is as follows:
Function addFn (dataOne, dataTwo ){
Var dataOneInt = dataOne. toString (). split (".") [0];
Var dataOneFloat = "";
Var dataTwoInt = dataTwo. toString (). split (".") [0];
Var dataTwoFloat = "";
Var lengthOne = 0;
Var lengthTwo = 0;
Var maxlength = 0;
If (dataOne. toString (). split ("."). length = 2 ){
DataOneFloat = dataOne. toString (). split (".") [1];
LengthOne = dataOneFloat. toString (). length;
}
If (dataTwo. toString (). split ("."). length = 2 ){
DataTwoFloat = dataTwo. toString (). split (".") [1];
LengthTwo = dataTwoFloat. toString (). length;
}
MaxLength = Math. max (lengthOne, lengthTwo );
For (var I = 0; I DataOneFloat + = "0 ";
}
For (var I = 0; I DataTwoFloat + = "0 ";
}
/**
* Multiple amplification of the two data
* Convert all of them to integers. Because integer calculation
* Relatively accurate.
*/
Var one = dataOneInt + "" + dataOneFloat;
Var two = dataTwoInt + "" + dataTwoFloat;
// Alert ("dataOne:" + dataOne + "dataTwo:" + dataTwo + "one:" + one + "two:" + two );
/**
* After the data is multiplied, the calculated result is,
* Then, reduce the number of equal multiples.
* Get the correct result.
*/
Var result = (Number (one) + Number (two)/Math. pow (10, maxLength );
Return result;
}