format amount split
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 将整数部分按每 4 位分组,适用于中文金额展示。
|
||||
* 例如:999999.99 -> 99,9999.99。
|
||||
*/
|
||||
export function formatWanInteger(value: number | string): string {
|
||||
const text = String(value).trim();
|
||||
const negative = text.startsWith("-");
|
||||
const integerText = (negative || text.startsWith("+")) ? text.slice(1) : text;
|
||||
const normalizedText = integerText.replace(/^0+(?=\d)/, "") || "0";
|
||||
const groupedText = normalizedText.replace(/\B(?=(\d{4})+(?!\d))/g, ",");
|
||||
return `${negative ? "-" : ""}${groupedText}`;
|
||||
}
|
||||
|
||||
/** 将整数分转换为带两位小数的金额展示文本。 */
|
||||
export function formatCentsAmount(cents?: number | null): string {
|
||||
if (cents === undefined || cents === null || !Number.isFinite(cents)) {
|
||||
return "未设置";
|
||||
}
|
||||
|
||||
const negative = cents < 0;
|
||||
const absolute = Math.abs(Math.trunc(cents));
|
||||
const yuan = Math.floor(absolute / 100);
|
||||
const fen = String(absolute % 100).padStart(2, "0");
|
||||
return `${negative ? "-" : ""}${formatWanInteger(yuan)}.${fen}`;
|
||||
}
|
||||
|
||||
/** 将元金额转换为按每 4 位分组的展示文本,最多保留两位小数。 */
|
||||
export function formatYuanAmount(value?: number | null): string {
|
||||
if (value === undefined || value === null || !Number.isFinite(value)) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
const [integerText, fractionText = ""] = value.toFixed(2).split(".");
|
||||
const normalizedFractionText = fractionText.replace(/0+$/, "");
|
||||
return `${formatWanInteger(integerText)}${normalizedFractionText ? `.${normalizedFractionText}` : ""}`;
|
||||
}
|
||||
Reference in New Issue
Block a user