export function formatCurrency(num, decimalPlaces = 2, prefix = "", suffix = "") { // 处理非数字情况 if (isNaN(num)) return "0.00"; // 转换为数字并四舍五入 const number = Number(num); const rounded = Math.round(number * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces); // 分割整数和小数部分 const parts = rounded.toString().split("."); const integerPart = parts[0]; const decimalPart = parts[1] || ""; // 整数部分添加千位分隔符 const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ","); // 处理小数部分(补零) const formattedDecimal = decimalPart.padEnd(decimalPlaces, "0").slice(0, decimalPlaces); // 组合结果 return `${prefix}${formattedInteger}${decimalPlaces > 0 ? "." + formattedDecimal : ""}${suffix}`; }