Example of precise addition and subtraction in js
- 2020-03-30 02:29:24
- OfStack
Calculate addition and subtraction exactly. For example, 0.1+0.2=0.3 or 0.1-0.2=-0.1
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<maxLength-lengthOne;i++){
dataOneFloat+="0";
}
for(var i=0;i<maxLength-lengthTwo;i++){
dataTwoFloat+="0";
}
var one=dataOneInt+""+dataOneFloat;
var two=dataTwoInt+""+dataTwoFloat;
//alert("dataOne:"+dataOne+" dataTwo:"+dataTwo +" one:"+one+" two:"+two);
var result= (Number(one)+Number(two))/Math.pow(10,maxLength);
return result;
}