AssetManager.UniApp/utils/currency.ts
claw_bot 365c461ea4 fix: 修复小程序编译兼容性问题
- 修改 tsconfig.json target 为 ES2019
- 修改 vite.config.ts 添加 build.target 和 esbuild.target 为 es2015
- 重写 currency.ts getCurrencySymbol 函数,避免使用可选链和空值合并操作符
2026-03-24 06:06:24 +00:00

71 lines
1.8 KiB
TypeScript

/**
* 货币工具函数
*/
import type { CurrencyCode } from '@/types/portfolio';
const CURRENCY_SYMBOLS: Record<string, string> = {
'CNY': '¥',
'USD': '$',
'HKD': 'HK$',
'EUR': '€',
'GBP': '£',
'JPY': '¥',
'SGD': 'S$',
'AUD': 'A$'
};
/**
* 获取货币符号
* @param currency - 货币代码 (CNY, USD, HKD 等)
* @returns 货币符号
*/
export function getCurrencySymbol(currency?: string): string {
// 兼容小程序:避免使用 ?. 和 ??
const code = currency ? currency.toUpperCase() : 'CNY';
return CURRENCY_SYMBOLS[code] || '¥';
}
/**
* 格式化金额
* @param amount - 金额
* @param currency - 货币代码
* @param decimals - 小数位数
* @returns 格式化后的金额字符串
*/
export function formatAmount(
amount: number,
currency: CurrencyCode | string = 'CNY',
decimals: number = 2
): string {
const symbol = getCurrencySymbol(currency);
const formatted = Math.abs(amount || 0).toLocaleString('zh-CN', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
});
const sign = amount >= 0 ? '' : '-';
return `${sign}${symbol}${formatted}`;
}
/**
* 格式化金额(带正负号)
* @param amount - 金额
* @param currency - 货币代码
* @param decimals - 小数位数
* @returns 格式化后的金额字符串
*/
export function formatAmountWithSign(
amount: number,
currency: CurrencyCode | string = 'CNY',
decimals: number = 2
): string {
const symbol = getCurrencySymbol(currency);
const formatted = Math.abs(amount || 0).toLocaleString('zh-CN', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
});
if (amount > 0) return `+${symbol}${formatted}`;
if (amount < 0) return `-${symbol}${formatted}`;
return `${symbol}${formatted}`;
}