金融类项目常用的工具函数

格式化金额 formatAmount

  • 该函数接受两个参数,amount 和 decimal。amount 是要格式化的金额,decimal 是要保留的小数位数。
  • 返回一个格式化后的金额字符串。

签名

function formatAmount(amount: number | string, decimal: number = 2): string;

参数

  • amount (number | string): 要格式化的金额,可以是数字或字符串。
  • decimal (number): 要保留的小数位数,默认为 2。

返回值

(string) 格式化后的金额字符串。

代码示例

type NumberType = number | string;
function formatAmount(amount: NumberType, decimal = 2) {
	// 将金额转换为字符串
	const amountStr = typeof amount === "string" ? amount : amount.toString();
	// 分割整数部分和小数部分
	let [integerPart, fractionalPart = ""] = amountStr.split(".");
	// 处理小数部分
	if (decimal > 0) {
		// 保留小数位并补零
		fractionalPart = fractionalPart.slice(0, decimal).padEnd(decimal, "0");
	}
	// 格式化整数部分
	const formatInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
	// 返回格式化结果
	return decimal > 0 ? `${formatInteger}.${fractionalPart}` : formatInteger;
}

恢复金额 restoreAmount

  • 该函数接受一个参数,amount,表示要恢复的金额。
  • 返回一个恢复后的金额字符串。

签名

function restoreAmount(amount: number | string): string;

参数

  • amount (number | string): 要恢复的金额,可以是数字或字符串。

返回值

(string) 恢复后的金额字符串。

代码示例

type NumberType = number | string;
function restoreAmount(amount: NumberType) {
	// 将输入转换为字符串
	const cleanedAmount = String(amount).replace(/,/g, "");
	// 分割整数部分和小数部分
	const [integerPart, fractionalPart = ""] = cleanedAmount.split(".");
	// 去掉整数部分的前导零
	const formattedInteger = integerPart.replace(/^0+/, "") || "0"; // 如果结果为空则返回 '0'
	// 处理小数部分,去掉末尾的零
	const formattedFractional = fractionalPart.replace(/0+$/, "");
	// 组合结果
	if (formattedFractional) {
		return `${formattedInteger}.${formattedFractional}`;
	} else {
		return formattedInteger; // 如果没有小数部分,返回整数部分
	}
}

比较金额大小 compareAmount

  • 该函数接受两个参数,amount1 和 amount2,表示要比较的金额。
  • 返回一个布尔值,表示金额大小关系。

签名

function compareAmount(amount: number | string): boolean;

参数

  • amount1 (number | string): 目标金额,可以是数字或字符串。
  • amount2 (number | string): 比较的金额,可以是数字或字符串。

返回值

(boolean) boolean 值,表示金额大小关系。true 表示 amount1 大于 amount2,false 表示 amount1 小于或等于 amount2

代码示例

type NumberType = number | string;
function compareAmount(amount1: NumberType, amount2: NumberType) {
	// 去掉前导零
	const resetAmount1 = restoreAmount(amount1);
	const resetAmount2 = restoreAmount(amount2);
	// 比较长度
	if (resetAmount1.length !== resetAmount2.length) {
		return resetAmount1.length > resetAmount2.length;
	}
	// 长度相同,逐字符比较
	return resetAmount1 > resetAmount2;
}

后续添加更多工具函数...

上次更新 2025/9/6 15:29:38