29 lines
1.0 KiB
TypeScript
29 lines
1.0 KiB
TypeScript
/** 金额展示(不依赖 Intl / toLocaleString,兼容微信小程序) */
|
|
export function toMoneyNumber(amount: unknown): number {
|
|
if (typeof amount === 'number') return Number.isFinite(amount) ? amount : 0;
|
|
if (typeof amount === 'string' && amount.trim()) {
|
|
const n = Number(amount);
|
|
return Number.isFinite(n) ? n : 0;
|
|
}
|
|
if (amount && typeof amount === 'object') {
|
|
const o = amount as { toNumber?: () => number; toString?: () => string };
|
|
if (typeof o.toNumber === 'function') {
|
|
const n = Number(o.toNumber());
|
|
if (Number.isFinite(n)) return n;
|
|
}
|
|
if (typeof o.toString === 'function' && o.toString !== Object.prototype.toString) {
|
|
const n = Number(o.toString());
|
|
if (Number.isFinite(n)) return n;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
export function formatMoney(amount: number | string): string {
|
|
const n = toMoneyNumber(amount);
|
|
const fixed = n.toFixed(2);
|
|
const [intPart, dec] = fixed.split('.');
|
|
const withComma = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
return `${withComma}.${dec}`;
|
|
}
|