js实现加减乘除 计算js丢失精度

js实现加减乘除 计算js丢失精度 /** * 公用方法 */ /********应用于几乎所有页面************** */ /** * 说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 返回值:arg1加上arg2的精确结果 * @param {*加数} arg1 * @param {*加数} arg2 * @param {*是否需要格式化} needFormat */ function accAdd(arg1, arg2, needFormat) { arg1 = parseFloat(arg1 + ""); arg2 = parseFloat(arg2 + ""); if (isNaN(arg1)) { arg1 = 0; } if (isNaN(arg2)) { arg2 = 0; } var result = (arg1 * 100 + arg2 * 100) / 100; needFormat && (result = keepDecimalFull(result, $ANumPosition)); return parseFloat(result) === 0 ? \'\' : result; } function accSub(arg1, arg2, needFormat) { arg1 = parseFloat(arg1 + ""); arg2 = parseFloat(arg2 + ""); if (isNaN(arg1)) { arg1 = 0; } if (isNaN(arg2)) { arg2 = 0; } var result = (arg1 * 100 - arg2 * 100) / 100; needFormat && (result = keepDecimalFull(result, $ANumPosition)); return parseFloat(result) === 0 ? \'\' : result; } /** * 乘法 * @param {*} arg1 * @param {*} arg2 * @param {*是否需要格式化} needFormat */ function accMulti(arg1, arg2, needFormat) { arg1 = parseFloat(arg1 + ""); arg2 = parseFloat(arg2 + ""); if (isNaN(arg1)) { arg1 = 0; } if (isNaN(arg2)) { arg2 = 0; } var result = arg1 * arg2; needFormat && (result = keepDecimalFull(result, $ANumPosition)); return parseFloat(result) === 0 ? \'\' : result; } /** * 除法 * @param {*被除数} Dividend * @param {*除数} Divisor * @param {*是否需要格式化} needFormat * @param {*是否生成百分比} isPercent * @param {*额外的小数位数保留} extraFormat */ function accDiv(Dividend, Divisor, needFormat, isPercent, extraFormat) { Dividend = parseFloat(Dividend + ""); Divisor = parseFloat(Divisor + ""); var result; if (isNaN(Dividend)) { Dividend = 0; } if (isNaN(Divisor)) { Divisor = 0; } if (Divisor === 0) { result = 0; } else { if (isPercent) { result = Dividend * 100 / Divisor; } else { result = Dividend / Divisor; } } needFormat && (result = keepDecimalFull(result, extraFormat ? extraFormat : $ANumPosition)); return parseFloat(result) === 0 ? \'\' : result; } /** * toFixed 四舍五入不精确 比如127.425 * @param {*数字} num * @param {*保留位数} pos */ function keepDecimalFull(num, pos) { var result = parseFloat(num); var decimal; var pos = pos || 2; var pos_multiple = 100; // 放大倍数 if(pos){ pos_multiple = 10; for(var i = 1;i < pos;i++){ pos_multiple *= 10; } } if (isNaN(result)) { result = 0; } result = Math.round(num * pos_multiple) / pos_multiple; decimal = result.toString(); // 补充小数点 var pos_decimal = decimal.indexOf(\'.\'); if (pos_decimal < 0) { pos_decimal = decimal.length; decimal += \'.\'; } while (decimal.length <= pos_decimal + pos) { decimal += \'0\'; } return decimal; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzxwxg.html