Home > Web Front-end > JS Tutorial > body text

Examples of precise calculations of addition and subtraction in js_javascript skills

WBOY
Release: 2016-05-16 16:53:56
Original
1238 people have browsed it

/精确计算加法和减法。例如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;

}
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!