- 新增热门帖子、热门作者、榜单接口及实现 - 新增api-documentation,更好的ai协作 - 修复types没有导出的问题 BREAKING CHANGES: 1.0.0->1.1.0(latest)
55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
// 数字格式化工具
|
|
export const numberUtils = {
|
|
// 格式化数字,添加千分位分隔符
|
|
format: (num: number, decimalPlaces: number = 0): string => {
|
|
if (isNaN(num)) return '0';
|
|
return num.toFixed(decimalPlaces).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
},
|
|
|
|
// 格式化大数字为K、M、B等形式
|
|
formatLarge: (num: number, decimalPlaces: number = 1): string => {
|
|
if (isNaN(num)) return '0';
|
|
|
|
const thresholds = [
|
|
{ value: 1, symbol: '' },
|
|
{ value: 1000, symbol: 'K' },
|
|
{ value: 1000000, symbol: 'M' },
|
|
{ value: 1000000000, symbol: 'B' },
|
|
{ value: 1000000000000, symbol: 'T' }
|
|
];
|
|
|
|
// 找到合适的阈值
|
|
const threshold = thresholds
|
|
.reverse()
|
|
.find(threshold => num >= threshold.value);
|
|
|
|
if (!threshold) return '0';
|
|
|
|
// 计算并格式化
|
|
const result = num / threshold.value;
|
|
return `${result.toFixed(decimalPlaces)}${threshold.symbol}`;
|
|
},
|
|
|
|
// 格式化数字为中文形式(万、亿等)
|
|
formatChinese: (num: number, decimalPlaces: number = 1): string => {
|
|
if (isNaN(num)) return '0';
|
|
|
|
const thresholds = [
|
|
{ value: 1, symbol: '' },
|
|
{ value: 10000, symbol: '万' },
|
|
{ value: 100000000, symbol: '亿' }
|
|
];
|
|
|
|
// 找到合适的阈值
|
|
const threshold = thresholds
|
|
.reverse()
|
|
.find(threshold => num >= threshold.value);
|
|
|
|
if (!threshold) return '0';
|
|
|
|
// 计算并格式化
|
|
const result = num / threshold.value;
|
|
return `${result.toFixed(decimalPlaces)}${threshold.symbol}`;
|
|
}
|
|
};
|