49 lines
1.7 KiB
TypeScript
49 lines
1.7 KiB
TypeScript
import Decimal from 'decimal.js';
|
|
|
|
export function formatNumber(value: number | string | undefined | null, decimals = 0): string {
|
|
if (value === undefined || value === null) return '-';
|
|
const num = typeof value === 'string' ? parseFloat(value) : value;
|
|
if (isNaN(num)) return '-';
|
|
// 使用确定性格式化,避免 SSR hydration 错误
|
|
const fixed = num.toFixed(decimals);
|
|
const parts = fixed.split('.');
|
|
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
return parts.join('.');
|
|
}
|
|
|
|
export function formatDecimal(value: string | number | undefined | null, precision = 7): string {
|
|
if (value === undefined || value === null) return '-';
|
|
try {
|
|
const decimal = new Decimal(value);
|
|
return decimal.toFixed(precision);
|
|
} catch {
|
|
return '-';
|
|
}
|
|
}
|
|
|
|
export function formatPercent(value: number | string | undefined | null, decimals = 2): string {
|
|
if (value === undefined || value === null) return '-';
|
|
const num = typeof value === 'string' ? parseFloat(value) : value;
|
|
if (isNaN(num)) return '-';
|
|
return `${(num * 100).toFixed(decimals)}%`;
|
|
}
|
|
|
|
export function formatCompactNumber(value: number | string | undefined | null): string {
|
|
if (value === undefined || value === null) return '-';
|
|
const num = typeof value === 'string' ? parseFloat(value) : value;
|
|
if (isNaN(num)) return '-';
|
|
|
|
if (num >= 1e12) return `${(num / 1e12).toFixed(2)}万亿`;
|
|
if (num >= 1e8) return `${(num / 1e8).toFixed(2)}亿`;
|
|
if (num >= 1e4) return `${(num / 1e4).toFixed(2)}万`;
|
|
return formatNumber(num);
|
|
}
|
|
|
|
export function formatPrice(value: string | number | undefined | null): string {
|
|
return formatDecimal(value, 8);
|
|
}
|
|
|
|
export function formatShareAmount(value: string | number | undefined | null): string {
|
|
return formatDecimal(value, 4);
|
|
}
|