From 765dbf07a0ba2cadb7ca0ad6174601e67ac60ccc Mon Sep 17 00:00:00 2001
From: yuan <123@>
Date: 星期二, 13 十月 2026 16:16:15 +0800
Subject: [PATCH] feat: 优化数值展示格式,去掉多余的结尾 0,统一金额和数量格式化

---
 src/utils/formatNumber.js |   75 +++++++++++++++++++++++++++++++++++++
 1 files changed, 75 insertions(+), 0 deletions(-)

diff --git a/src/utils/formatNumber.js b/src/utils/formatNumber.js
new file mode 100644
index 0000000..af819be
--- /dev/null
+++ b/src/utils/formatNumber.js
@@ -0,0 +1,75 @@
+/**
+ * 鏁板瓧灞曠ず鏍煎紡鍖栧伐鍏�
+ *
+ * 璇存槑锛氬悗绔噾棰�/鏁伴噺瀛楁缁熶竴鎸� 6 浣嶅皬鏁拌繑鍥烇紙濡� 52333.580000锛夛紝
+ * 鐩存帴灞曠ず浼氬嚭鐜板ぇ閲忔棤鎰忎箟鐨勭粨灏� 0锛岃繖閲岀粺涓�鍋氬睍绀哄眰澶勭悊銆�
+ */
+
+/**
+ * 鍘绘帀灏忔暟鏈熬澶氫綑鐨� 0锛堟渶澶氫繚鐣� maxDecimals 浣嶅皬鏁帮級
+ * 渚嬶細52333.580000 -> 52333.58 锛�100.000000 -> 100 锛�0.000000 -> 0
+ *     474235.654230 -> 474235.65423
+ * @param {string|number} value 鍘熷鍊�
+ * @param {number} maxDecimals 鏈�澶氫繚鐣欑殑灏忔暟浣嶏紝榛樿 6
+ * @returns {string} 鏍煎紡鍖栧悗鐨勫瓧绗︿覆
+ */
+export const trimZeros = (value, maxDecimals = 6) => {
+  if (value === undefined || value === null || value === "") {
+    return "0";
+  }
+  const num = typeof value === "number" ? value : Number(value);
+  // 闈炴暟瀛楋紙濡� "-"銆�"--"锛夊師鏍疯繑鍥烇紝閬垮厤鎶婂崰浣嶇鏄剧ず鎴� 0
+  if (!Number.isFinite(num)) {
+    return String(value);
+  }
+  const decimals = Math.min(20, Math.max(0, Math.floor(maxDecimals)));
+  let text = num.toFixed(decimals);
+  if (decimals > 0 && text.includes(".")) {
+    text = text.replace(/0+$/, "").replace(/\.$/, "");
+  }
+  // 澶勭悊 -0.000000 杩欑被缁撴灉
+  if (text === "" || text === "-" || text === "-0") {
+    text = "0";
+  }
+  return text;
+};
+
+/**
+ * 鍥涜垗浜斿叆鍒版寚瀹氬皬鏁颁綅锛堟寜鍗佽繘鍒惰涔夛級
+ * JS 鍘熺敓鐨� toFixed 浼氬彈浜岃繘鍒舵诞鐐瑰奖鍝嶏紝渚嬪 (926163.765).toFixed(2) 寰楀埌 "926163.76"锛�
+ * 鑰屾寜鍗佽繘鍒跺洓鑸嶄簲鍏ュ簲涓� 926163.77锛岃繖閲岀粺涓�鎴愪笌鏁版嵁搴� ROUND 涓�鑷寸殑缁撴灉銆�
+ * @param {string|number} value 鍘熷鍊�
+ * @param {number} decimals 灏忔暟浣嶆暟锛岄粯璁� 2
+ * @returns {number} 鍥涜垗浜斿叆鍚庣殑鏁板瓧
+ */
+export const roundHalfUp = (value, decimals = 2) => {
+  const num = Number(value);
+  const digits = Math.min(20, Math.max(0, Math.floor(decimals)));
+  if (!Number.isFinite(num)) {
+    return 0;
+  }
+  // 绉戝璁℃暟娉曪紙濡� 1e-7锛夎蛋鍘熺敓 toFixed锛岄伩鍏嶅瓧绗︿覆鎷兼帴鍑� "1e-7e2"
+  const text = String(num);
+  if (text.includes("e") || text.includes("E")) {
+    return Number(num.toFixed(digits));
+  }
+  return Number(`${Math.round(Number(`${text}e${digits}`))}e-${digits}`);
+};
+
+/**
+ * 鍥哄畾淇濈暀鎸囧畾灏忔暟浣嶏紙涓嶈冻琛� 0锛�
+ * 渚嬶細2296268.351 -> 2296268.35 锛坉ecimals = 2锛�
+ * @param {string|number} value 鍘熷鍊�
+ * @param {number} decimals 灏忔暟浣嶆暟锛岄粯璁� 2
+ * @returns {string} 鏍煎紡鍖栧悗鐨勫瓧绗︿覆
+ */
+export const toFixedNumber = (value, decimals = 2) => {
+  const num = Number(value);
+  const digits = Math.min(20, Math.max(0, Math.floor(decimals)));
+  if (!Number.isFinite(num)) {
+    return (0).toFixed(digits);
+  }
+  const text = num.toFixed(digits);
+  // 閬垮厤鍑虹幇 "-0.00" 杩欑被璐熼浂鏄剧ず
+  return parseFloat(text) === 0 ? text.replace(/^-/, "") : text;
+};

--
Gitblit v1.9.3