format.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * @Author: code4eat awesomedema@gmail.com
  3. * @Date: 2022-12-14 14:14:32
  4. * @LastEditors: code4eat awesomedema@gmail.com
  5. * @LastEditTime: 2025-04-30 14:52:04
  6. * @FilePath: /BudgetManaSystem/src/utils/format.ts
  7. * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
  8. */
  9. // 示例方法,没有实际意义
  10. export function trim(str: string) {
  11. return str.trim();
  12. }
  13. // 定义金额格式化选项的接口
  14. interface FormatMoneyOptions {
  15. decimalPlaces?: number; // 指定小数位数
  16. useThousandSeparator?: boolean; // 是否使用千分号
  17. }
  18. //金额数字转换
  19. export function formatMoneyNumber(num: number | string | undefined | null, options?: FormatMoneyOptions) {
  20. if (num === undefined || num === null || num === '') {
  21. return '-'; // 对于空值或未定义值,返回 "-"
  22. }
  23. const numberToFormat = Number(num);
  24. if (isNaN(numberToFormat)) {
  25. return String(num); // 如果转换后不是有效数字,则返回原始字符串形式
  26. }
  27. // 默认小数位数为2,除非在选项中指定
  28. const minimumFractionDigits = options?.decimalPlaces !== undefined ? options.decimalPlaces : 2;
  29. const maximumFractionDigits = options?.decimalPlaces !== undefined ? options.decimalPlaces : 2;
  30. // 默认使用千分号,除非在选项中明确设置为 false
  31. const useGrouping = options?.useThousandSeparator === true;
  32. return new Intl.NumberFormat('en-US', {
  33. minimumFractionDigits: minimumFractionDigits,
  34. maximumFractionDigits: maximumFractionDigits,
  35. useGrouping: useGrouping, // 控制是否使用千分号
  36. }).format(numberToFormat);
  37. }
  38. export function formatToPercentage(num: number) {
  39. if (typeof num !== 'number' || isNaN(num)) {
  40. return num;
  41. }
  42. return new Intl.NumberFormat('en-US', {
  43. style: 'percent',
  44. minimumFractionDigits: 2,
  45. maximumFractionDigits: 2,
  46. }).format(num);
  47. }