jquery數值精度計算
阿新 • • 發佈:2018-07-20
() tar jquer str fix float 動態 {} cat
/** *判斷數值是否相等 * @param source 原比較數據 * @param target 目標比較數據 * @param accuracy 精度值 * @returns {boolean} */ isEqual:function(source,target,accuracy){ accuracy = accuracy == undefined ? 10:accuracy; //默認精度位10 returnparseFloat(source).toFixed(accuracy) === parseFloat(target).toFixed(accuracy); } /** *數值相加 * @param firstNumber * @param lastNumber * @returns {number} */ accuracyAdd:function(firstNumber,lastNumber){ var num1,num2,m;try{num1=firstNumber.toString().split(".")[1].length}catch(e){num1=0}; try{num2=lastNumber.toString().split(".")[1].length}catch(e){num2=0}; m=Math.pow(10,Math.max(num1,num2)); return (firstNumber*m+lastNumber*m)/m; } /** * 數值相減 * @param firstNumber * @param lastNumber * @returns {string}*/ accuracySub:function(firstNumber,lastNumber){ var r1,r2,m,n; try{r1=firstNumber.toString().split(".")[1].length}catch(e){r1=0} try{r2=lastNumber.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)); //last modify by deeka //動態控制精度長度 n=(r1>=r2)?r1:r2; return ((firstNumber*m-lastNumber*m)/m).toFixed(n); } /** * 除法函數,兩數相除 * @param arg1 * @param arg2 * @returns {number} */ accuracyDiv:function(arg1,arg2){ var t1=0,t2=0,r1,r2; try{t1=arg1.toString().split(".")[1].length}catch(e){} try{t2=arg2.toString().split(".")[1].length}catch(e){} with(Math){ r1=Number(arg1.toString().replace(".","")) r2=Number(arg2.toString().replace(".","")) return (r1/r2)*pow(10,t2-t1); } } /** * 乘法函數,兩數相乘 * @param arg1 * @param arg2 * @returns {number} */ accuracyMul:function(arg1,arg2) { var m=0,s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(".")[1].length}catch(e){} try{m+=s2.split(".")[1].length}catch(e){} return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) }
jquery數值精度計算