In javascript, when you use decimal places for addition, subtraction, multiplication, division, you will find that the result is sometimes followed by a long decimal point, which makes the operation complex and affects the calculation result. The reason for a query on the internet is roughly as follows: In javascript, there will always be many decimal places during the computation of decimal data, because the computation of floating point numbers in javascript is calculated in binary notation.
Copy codeThe Code is as follows:
/**
* Addition operation to avoid the loss of Multiple Digits and computing accuracy after adding decimal points to the data.
*
* @ Param num1 addend 1 | num2 addend 2
*/
Function numAdd (num1, num2 ){
Var baseNum, baseNum1, baseNum2;
Try {
BaseNum1 = num1.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum1 = 0;
}
Try {
BaseNum2 = num2.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum2 = 0;
}
BaseNum = Math. pow (10, Math. max (baseNum1, baseNum2 ));
Return (num1 * baseNum + num2 * baseNum)/baseNum;
};
/**
* Addition operation to Avoid Multiple Digits and loss of computing accuracy after decimal point subtraction of data.
*
* @ Param num1 subtrahend | num2 subtrahend
*/
Function numSub (num1, num2 ){
Var baseNum, baseNum1, baseNum2;
Var precision; // Accuracy
Try {
BaseNum1 = num1.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum1 = 0;
}
Try {
BaseNum2 = num2.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum2 = 0;
}
BaseNum = Math. pow (10, Math. max (baseNum1, baseNum2 ));
Precision = (baseNum1> = baseNum2 )? BaseNum1: baseNum2;
Return (num1 * baseNum-num2 * baseNum)/baseNum). toFixed (precision );
};
/**
* The multiplication operation prevents the loss of Multiple Digits and computing accuracy after the decimal point is multiplied by the data.
*
* @ Param num1 multiplier | num2 Multiplier
*/
Function numMulti (num1, num2 ){
Var baseNum = 0;
Try {
BaseNum + = num1.toString (). split (".") [1]. length;
} Catch (e ){
}
Try {
BaseNum + = num2.toString (). split (".") [1]. length;
} Catch (e ){
}
Return Number (num1.toString (). replace (". "," ") * Number (num2.toString (). replace (". "," ")/Math. pow (10, baseNum );
};
/**
* Division operation to Avoid Multiple Digits and loss of computing accuracy after the decimal point is exceeded.
*
* @ Param num1 divisor | num2 Divisor
*/
Function numDiv (num1, num2 ){
Var baseNum1 = 0, baseNum2 = 0;
Var baseNum3, baseNum4;
Try {
BaseNum1 = num1.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum1 = 0;
}
Try {
BaseNum2 = num2.toString (). split (".") [1]. length;
} Catch (e ){
BaseNum2 = 0;
}
With (Math ){
BaseNum3 = Number (num1.toString (). replace (".",""));
BaseNum4 = Number (num2.toString (). replace (".",""));
Return (baseNum3/baseNum4) * pow (10, baseNum2-baseNum1 );
}
};