Example of exact addition and subtraction in js

Source: Internet
Author: User

/Accurately calculate addition and subtraction. For example, 0.1 + 0.2 = 0.3 or 0.1-0.2 =-0.1
Copy codeThe 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 <maxLength-lengthOne; I ++ ){
DataOneFloat + = "0 ";
}
For (var I = 0; I <maxLength-lengthTwo; 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;

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.