25 lines
778 B
TypeScript
25 lines
778 B
TypeScript
export function formatMoney(cents: number, currency = "CNY", locale = "zh-CN"): string {
|
|
return new Intl.NumberFormat(locale, {
|
|
style: "currency",
|
|
currency,
|
|
minimumFractionDigits: 2,
|
|
maximumFractionDigits: 2,
|
|
}).format(cents / 100);
|
|
}
|
|
|
|
export const money = formatMoney;
|
|
|
|
export function centsToAmount(cents: number): string {
|
|
return (cents / 100).toFixed(2);
|
|
}
|
|
|
|
export function amountToCents(value: string): number {
|
|
const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
|
|
if (!match) throw new Error("INVALID_AMOUNT");
|
|
const cents = Number(match[1]) * 100 + Number((match[2] ?? "").padEnd(2, "0"));
|
|
if (!Number.isSafeInteger(cents) || cents <= 0) throw new Error("INVALID_AMOUNT");
|
|
return cents;
|
|
}
|
|
|
|
export const yuanToCents = amountToCents;
|