41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
// ============================================================
|
|
// 模拟项目 — src/formatter.ts
|
|
// ============================================================
|
|
|
|
export interface FormatOptions {
|
|
decimals: number;
|
|
prefix: string;
|
|
suffix: string;
|
|
locale: string;
|
|
}
|
|
|
|
export class Formatter {
|
|
format(value: number, options: FormatOptions): string {
|
|
const { decimals, prefix, suffix, locale } = options;
|
|
const formatted = value.toLocaleString(locale, {
|
|
minimumFractionDigits: decimals,
|
|
maximumFractionDigits: decimals,
|
|
});
|
|
return `${prefix}${formatted}${suffix}`;
|
|
}
|
|
|
|
formatPercent(value: number, decimals: number = 1): string {
|
|
return `${(value * 100).toFixed(decimals)}%`;
|
|
}
|
|
|
|
formatCurrency(value: number, currency: string = "USD"): string {
|
|
return value.toLocaleString("en-US", {
|
|
style: "currency",
|
|
currency,
|
|
});
|
|
}
|
|
|
|
truncate(value: number, maxLength: number): string {
|
|
const str = value.toString();
|
|
if (str.length <= maxLength) {
|
|
return str;
|
|
}
|
|
return str.slice(0, maxLength) + "...";
|
|
}
|
|
}
|