Browse Source

解决精度丢失的问题

Lijy 1 năm trước cách đây
mục cha
commit
eaef85fe8d

+ 39 - 0
fhKeeper/formulahousekeeper/timesheet-workshop/src/common/js/compute.js

@@ -0,0 +1,39 @@
+export default {
+  // 加法函数,用来得到精确的加法结果
+  // 返回:arg1 + arg2 的精确结果
+  accAdd: function (arg1, arg2) {
+    var r1, r2, m;
+    try {
+      r1 = arg1.toString().split(".")[1].length;
+    } catch (e) {
+      r1 = 0;
+    }
+    try {
+      r2 = arg2.toString().split(".")[1].length;
+    } catch (e) {
+      r2 = 0;
+    }
+    m = Math.pow(10, Math.max(r1, r2));
+    return (arg1 * m + arg2 * m) / m;
+  },
+
+  // 减法函数,用来得到精确的减法结果
+  // 返回:arg1 - arg2 的精确结果
+  accSub: function (arg1, arg2) {
+    var r1, r2, m, n;
+    try {
+      r1 = arg1.toString().split(".")[1].length;
+    } catch (e) {
+      r1 = 0;
+    }
+    try {
+      r2 = arg2.toString().split(".")[1].length;
+    } catch (e) {
+      r2 = 0;
+    }
+    m = Math.pow(10, Math.max(r1, r2));
+    // 动态控制精度长度
+    n = r1 >= r2 ? r1 : r2;
+    return ((arg1 * m - arg2 * m) / m).toFixed(n);
+  },
+};

+ 3 - 1
fhKeeper/formulahousekeeper/timesheet-workshop/src/views/product/list.vue

@@ -635,6 +635,7 @@ import util from "../../common/js/util";
 // 自定义select组件
 import selectCat from "@/components/select.vue"
 import { version } from 'vue';
+import calculation from '../../common/js/compute.js';
 export default {
     components: {
         selectCat
@@ -940,7 +941,8 @@ export default {
         },
         priceSingleTotal: function () {
             return this.procedureLit.reduce((total, item) => {
-                return +total + +item.unitPrice
+                // return +total + +item.unitPrice
+                return calculation.accAdd(+total, +item.unitPrice)
             }, 0)
         },
     },