/** * 数字展示格式化工具 * * 说明:后端金额/数量字段统一按 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 (decimals = 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; };