Home  >  Article  >  Web Front-end  >  Examples of precise calculations of addition and subtraction in js_javascript skills

Examples of precise calculations of addition and subtraction in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:53:561244browse

/精确计算加法和减法。例如0.1 0.2=0.3或 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;idataOneFloat ="0";
}
for(var i=0;idataTwoFloat ="0";
}

/**
* Multiply the two data
* to make them both integers. Because integer calculation
* is more accurate.
*/
var one=dataOneInt "" dataOneFloat;
var two=dataTwoInt "" dataTwoFloat;
//alert("dataOne:" dataOne " dataTwo:" dataTwo " one:" one " two:" two);

/**
*After the data is expanded by a multiple, the calculated result is obtained,
*and then reduced by the same multiple
* to obtain the correct result
*/
var result= (Number(one) Number(two))/Math.pow(10,maxLength);

return result;

}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn