formatCurrency.ts 826 B

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