Files
doodle-mini/miniprogram/core/utils/format.ts
T
2026-03-27 17:31:52 +08:00

49 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 展示层格式化(无 i18n 框架依赖,供 UI / Canvas 文案使用)
*/
/** 适龄文案,如 3-5岁 */
export function formatAgeRangeLabel(minAge: number, maxAge: number): string {
return `${minAge}-${maxAge}岁`;
}
/** 比较符号(全角,与现有比大小题型一致) */
export function formatCompareSymbol(
relation: 'gt' | 'lt' | 'eq',
): '' | '' | '' {
switch (relation) {
case 'gt':
return '';
case 'lt':
return '';
default:
return '';
}
}
/** 数字左侧补零,如 padLeadingZero(3, 2) => "03" */
export function padLeadingZero(num: number, width: number): string {
const s = String(Math.trunc(Math.abs(num)));
if (s.length >= width) return num < 0 ? `-${s}` : s;
const pad = '0'.repeat(width - s.length);
return num < 0 ? `-${pad}${s}` : `${pad}${s}`;
}
/** 截断过长字符串 */
export function truncateText(
text: string,
maxChars: number,
ellipsis = '…',
): string {
if (text.length <= maxChars) return text;
const cut = Math.max(0, maxChars - ellipsis.length);
return text.slice(0, cut) + ellipsis;
}
/** 非负整数千分位(中文场景常用逗号或空格,此处用半角逗号) */
export function formatThousands(n: number): string {
const i = Math.trunc(n);
if (i < 0) return `-${formatThousands(-i)}`;
return String(i).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}