lrf 2 years ago
parent
commit
78db1d0d8f
2 changed files with 50 additions and 0 deletions
  1. 1 0
      package.json
  2. 49 0
      src/util/computed.js

+ 1 - 0
package.json

@@ -14,6 +14,7 @@
     "@wangeditor/editor-for-vue": "^1.0.2",
     "axios": "^0.27.2",
     "core-js": "^3.6.5",
+    "decimal.js": "^10.4.3",
     "echarts": "^5.4.0",
     "element-ui": "^2.15.10",
     "exceljs": "^4.3.0",

+ 49 - 0
src/util/computed.js

@@ -0,0 +1,49 @@
+'use strict';
+const Decimal = require('decimal.js');
+const _ = require('lodash');
+// Decimal.set({ precision: 2 });
+module.exports = {
+  turnDecimal(n) {
+    if (_.isObject(n)) {
+      n = JSON.parse(JSON.stringify(n));
+      if (_.isObject(n)) n = _.get(n, '$numberDecimal');
+    }
+    return new Decimal(n);
+  },
+  // 加法
+  plus(n1 = 0, n2 = 0) {
+    const number1 = this.turnDecimal(n1);
+    const number2 = this.turnDecimal(n2);
+    const result = number1.add(number2).toFixed(2, Decimal.ROUND_DOWN);
+    return this.toNumber(result);
+  },
+  // 减法
+  minus(n1 = 0, n2 = 0) {
+    const number1 = this.turnDecimal(n1);
+    const number2 = this.turnDecimal(n2);
+    const result = number1.minus(number2).toFixed(2, Decimal.ROUND_DOWN);
+    return this.toNumber(result);
+  },
+  // 乘法
+  multiply(n1 = 0, n2 = 0) {
+    const number1 = this.turnDecimal(n1);
+    const number2 = this.turnDecimal(n2);
+    const result = number1.mul(number2).toFixed(2, Decimal.ROUND_DOWN);
+    return this.toNumber(result);
+  },
+  // 除法
+  divide(n1 = 0, n2 = 0) {
+    const number1 = this.turnDecimal(n1);
+    const number2 = this.turnDecimal(n2);
+    const result = number1.div(number2).toFixed(2, Decimal.ROUND_DOWN);
+    return this.toNumber(result);
+  },
+
+  toNumber(num) {
+    if (_.isObject(num)) {
+      num = JSON.parse(JSON.stringify(num));
+      if (_.isObject(num)) num = _.get(num, '$numberDecimal');
+    }
+    return new Decimal(num).toNumber();
+  },
+};