Home > Article > Web Front-end > Example of implementing precise addition, subtraction, multiplication and division using JS
In the project, JS is used to implement automatic calculation. When performing some floating point calculations, the calculation result is a long list of values. This article mainly shares with you examples of JS realizing precise addition, subtraction, multiplication and division. I hope it can help everyone. .
The specific code is as follows:
//加法函数 2 function accAdd(arg1, arg2) { 3 var r1, r2, m; 4 try { 5 r1 = arg1.toString().split(".")[1].length; 6 } 7 catch (e) { 8 r1 = 0; 9 } 10 try { 11 r2 = arg2.toString().split(".")[1].length; 12 } 13 catch (e) { 14 r2 = 0; 15 } 16 m = Math.pow(10, Math.max(r1, r2)); 17 return (arg1 * m + arg2 * m) / m; 18 } 19 //给Number类型增加一个add方法,,使用时直接用 .add 即可完成计算。 20 Number.prototype.add = function (arg) { 21 return accAdd(arg, this); 22 }; 23 24 25 //减法函数 26 function Subtr(arg1, arg2) { 27 var r1, r2, m, n; 28 try { 29 r1 = arg1.toString().split(".")[1].length; 30 } 31 catch (e) { 32 r1 = 0; 33 } 34 try { 35 r2 = arg2.toString().split(".")[1].length; 36 } 37 catch (e) { 38 r2 = 0; 39 } 40 m = Math.pow(10, Math.max(r1, r2)); 41 //last modify by deeka 42 //动态控制精度长度 43 n = (r1 >= r2) ? r1 : r2; 44 return ((arg1 * m - arg2 * m) / m).toFixed(n); 45 } 46 47 //给Number类型增加一个add方法,,使用时直接用 .sub 即可完成计算。 48 Number.prototype.sub = function (arg) { 49 return Subtr(this, arg); 50 }; 51 52 53 //乘法函数 54 function accMul(arg1, arg2) { 55 var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); 56 try { 57 m += s1.split(".")[1].length; 58 } 59 catch (e) { 60 } 61 try { 62 m += s2.split(".")[1].length; 63 } 64 catch (e) { 65 } 66 return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); 67 } 68 //给Number类型增加一个mul方法,使用时直接用 .mul 即可完成计算。 69 Number.prototype.mul = function (arg) { 70 return accMul(arg, this); 71 }; 72 73 74 //除法函数 75 function accDiv(arg1, arg2) { 76 var t1 = 0, t2 = 0, r1, r2; 77 try { 78 t1 = arg1.toString().split(".")[1].length; 79 } 80 catch (e) { 81 } 82 try { 83 t2 = arg2.toString().split(".")[1].length; 84 } 85 catch (e) { 86 } 87 with (Math) { 88 r1 = Number(arg1.toString().replace(".", "")); 89 r2 = Number(arg2.toString().replace(".", "")); 90 return (r1 / r2) * pow(10, t2 - t1); 91 } 92 } 93 //给Number类型增加一个div方法,,使用时直接用 .div 即可完成计算。 94 Number.prototype.div = function (arg) { 95 return accDiv(this, arg); 96 };
The usage method is as follows:
//加法示例(其它的都类似) 2 function calculate() { 3 //数字1 4 var num1 = 10; 5 //数字2 6 var num2 = 5; 7 //计算 num1 + num2 8 alert(num1.add(num2)); 9 }
Related recommendations:
js accurate addition, subtraction, multiplication and division explanation
The above is the detailed content of Example of implementing precise addition, subtraction, multiplication and division using JS. For more information, please follow other related articles on the PHP Chinese website!