In JavaScript, when you use decimals to perform addition, subtraction, multiplication and division operations, you will find that the result obtained is sometimes followed by a long decimal, which makes the operation complicated and affects the calculation results. I searched the Internet for the reasons, which are roughly as follows: In JavaScript, many decimal places will always appear when data operations with decimals. This is because in JavaScript, floating point numbers are calculated in 2-digit.
The code copy is as follows:
/**
* Addition operation to avoid multi-digit numbers and calculation accuracy losses after adding decimal points to data.
*
* @param num1 add number 1 | num2 add number 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 multi-digit numbers and calculation accuracy losses after decreasing the data phase.
*
* @param num1 is subtracted|num2 is subtracted
*/
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);
};
/**
* Multiplication operation to avoid multi-digit numbers and calculation accuracy losses after multiplying data by decimal points.
*
* @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 multi-digit numbers and calculation accuracy losses after dividing the decimal point of the data.
*
* @param num1 dividend|num2 dividend
*/
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);
}
};