'use strict'; /** * * @author Mai * @date * @version */ ;const zhBaseCalc = (function () { const zeroPrecision = 12, mulPrecision = 12, divPrecision = 12; function digitLength (num) { // 兼容科学计数 var eSplit = num.toString().split(/[eE]/); var len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0)); return len > 0 ? len : 0; } function powLength (num) { var rs = num.toString(); if (rs.indexOf('+') > 0) { return rs.match(/0*$/g).length(); } else { const eSplit = rs.split(/[eE]/); const len = Number(eSplit[1]) - this.digitLength(eSplit[0]); return len > 0 ? len : 0; } } function round (num, digit) { return Math.round(num * Math.pow(10, digit)) / Math.pow(10, digit); } function add(num1, num2) { var d1 = this.digitLength(num1), d2 = this.digitLength(num2); return this.round(num1 + num2, Math.max(d1, d2)); } function sub(num1, num2) { var d1 = this.digitLength(num1), d2 = this.digitLength(num2); return this.round(num1 - num2, Math.max(d1, d2)); } function mul(num1, num2) { return this.round(num1 * num2, mulPrecision); } function div(num1, num2) { return this.round(num1 / num2, divPrecision); } function isNonZero(num) { return num && round(num, zeroPrecision) !== 0; } return { digitLength: digitLength, powLength: powLength, round: round, add: add, sub: sub, mul: mul, div: div, isNonZero: isNonZero, } })(); /** * 计算(四则、舍入) 统一,方便以后置换 * @type {{add, sub, mul, div, round}} */ const ZhCalc = (function () { Decimal.set({precision: 50, defaults: true}); /** * 加法 num1 + num2 * @param num1 * @param num2 * @returns {number} */ function add(num1, num2) { //return zhBaseCalc.add(num1 ? num1 : 0, num2 ? num2: 0); return num1 ? (num2 ? zhBaseCalc.add(num1, num2) : num1) : num2; }; /** * 减法 num1 - num2 * @param num1 * @param num2 * @returns {number} */ function sub(num1, num2) { return zhBaseCalc.sub(num1 ? num1 : 0, num2 ? num2 : 0); } /** * 乘法 num1 * num2 * @param num1 * @param num2 * @returns {*} */ function mul(num1, num2, digit = 6) { //return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber(); return (num1 && num2) ? (Decimal.mul(num1, num2).toDecimalPlaces(digit).toNumber()) : 0; } /** * 除法 num1 / num2 * @param num1 - 被除数 * @param num2 - 除数 * @returns {*} */ function div(num1, num2, digit = 6) { if (num2 && !checkZero(num2)) { //return Decimal.div(num1 ? num1: 0, num2).toDecimalPlaces(digit).toNumber(); return num1 ? (Decimal.div(num1, num2).toDecimalPlaces(digit).toNumber()) : 0; } else { return null; } } /** * 四舍五入 * @param {Number} value - 舍入的数字 * @param {Number} decimal - 要保留的小数位数 * @returns {*} */ function round(value, decimal) { return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null; } return {add, sub, mul, div, round, isNonZero: zhBaseCalc.isNonZero} })();